Reputation: 2017
One day I saw certain way to swap elements in array. Like this:
var arr = [1,2,3];
arr[0] = [arr[1], arr[1] = arr[0]][0];
Obviously this method assume that first value of temporary array arr[1]
will be calculated before second arr[1] = arr[0]
.
Otherway both values will be the same. Synthetic example:
var x = 1;
var arr = [x, x += 1, x += 1];
arr; // [1,2,3] or [3,3,2] or maybe [3,2,3]?
Is there any guarantees that javascript interpreter will not act in this manner?
Upvotes: 1
Views: 156
Reputation: 215009
JS array initializers are guaranteed to be evaluated left-to-right
ArrayAccumulation(ElementList : ElementList , Elision[opt] AssignmentExpression):
.1. Let postIndex be the result of performing ArrayAccumulation for ElementList with arguments array and nextIndex...
.4. Let initResult be the result of evaluating AssignmentExpression.
@http://www.ecma-international.org/ecma-262/6.0/#sec-runtime-semantics-arrayaccumulation
It's better not to rely on that though.
Upvotes: 2