1

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

"It's better not to rely on that though." - Huh? You absolutely can rely on it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.