You-Dont-Know-JS icon indicating copy to clipboard operation
You-Dont-Know-JS copied to clipboard

Types & Grammar: Associativity

Open astericky opened this issue 12 years ago • 4 comments

I managed to answer all of the test questions correctly but I don’t see how it is clear there is right associativity with the ternary operator. Am I to under stand this as ternary operator processes the right most item first even though it may never get used. Seems like it wouldn’t be very performant to run code that may or may not need to be run. What am I missing here?

astericky avatar Nov 16 '14 20:11 astericky

You're mostly missing this part:

It's important to note that associativity is not the same thing as left-to-right or right-to-left processing.

Try for instance this (modified first example):

function logSomething() {
  console.log("something");
  return true;
}

true ? false : logSomething() ? true : true;      // false -- does not log anything
true ? false : (logSomething() ? true : true);    // false -- does not log anything
(true ? false : logSomething()) ? true : true;    // true -- does not log anything

and you'll see that right-to-left associativity does not imply right-to-left processing; associativity is only about how parentheses "are set" when you omit them.

cobalamin avatar Nov 16 '14 20:11 cobalamin

I think it's important to go back and quote some parts from chapter 5 to clarify:

In general, operators are either left-associative or right-associative, referring to whether grouping happens from the left or from the right.

It's important to note that associativity is not the same thing as left-to-right or right-to-left processing.

...with an expression like a && b && c, grouping will happen implicitly, meaning that either a && b or b && c will be evaluated first.

The fact that ? : is "right associative" has nothing to do with whether in a ? b : c the b or c is processed first. Associativity doesn't matter when there is only one occurrence of the operator in the expression, because grouping will not occur.

Instead, it has everything to do with the grouping when two or more occurrences of the operator occur in the expression.

getify avatar Nov 16 '14 20:11 getify

I get it now. now that you say associativity is about where the parenthesis are in the background when there are no parenthesis... When I see parenthesis I think they have to process first when it really isn't that. I think I was over thinking it. Thanks guys for addressing my issues.

astericky avatar Nov 16 '14 20:11 astericky

:)

getify avatar Nov 16 '14 21:11 getify