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?

asked Jul 1, 2016 at 10:11

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.

answered Jul 1, 2016 at 10:17
1
  • 1
    "It's better not to rely on that though." - Huh? You absolutely can rely on it. Commented Jul 1, 2016 at 11:01

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.