Reputation: 6230
I have written the following code
o[s += "a"] = o[s += "b"] = o[s += "c"] = 0;
I was curious as to why the variable s
ends up storing "abc" and not "cba". It seems like it would be easier for the the code to execute from right to left.
I seems as though the executor chooses and index for storage then decides what goes in there, but doing this make it sound slower since there would be so many states and memory being pushed onto the stack. Can somebody explain as to why it makes sense for the code to execute in the order that is does?
I have included a fiddle with a few more examples. http://jsfiddle.net/eggrdtuk/3/
Upvotes: 3
Views: 54
Reputation: 1129
Luke's comment is right. We can look at the MDN page for operator precedence.
Computed Member Access has precedence 1 and Assignment has precedence 16. So the property access expressions are evaluated first, then the assignment operations. Furthermore, Computed Member Access has left-to-right associativity, while Assignment has right-to-left associativity.
So, we can think of the first step as parsing the property access expressions from left-to-right:
o["a"] = o["ab"] = o["abc"] = 0
and the second step as doing assigments from right-to-left:
(o["a"] = (o["ab"] = (o["abc"] = 0)))
(o["a"] = (o["ab"] = 0))
(o["a"] = 0)
I don't see how changing associativity for either step would change the performance. But if there is a reason, I would love to learn :)
Upvotes: 4