Attribute Evaluation Order in Javascript Object Literals

I would like to write something like this (in Javascript):

var obj = { left: left, right: -(left += increment) };

      

This will only do what I want, if I can be sure that the attribute values โ€‹โ€‹will be evaluated in the same order I write them. Does the language provide such a guarantee anywhere?

+2


source to share


1 answer


From ECMA 3rd Edition Specification :

The original ECMAScript program is first converted into a sequence of input elements, which are either tokens, line delimiters, comments, or spaces. The source text is scanned from left to right, repeatedly taking as many characters as possible as the next input element.

In other words, yes, the spec addresses this. This code should always work:



var left = 5, increment = 1;
var obj = { left: left, right: -(left += increment) };
// obj.left  ===  5
// obj.right === -6

      

This is NOT the order of the attributes as they are stored in the object, but rather the order in which JavaScript will evaluate your statement: left to right, up to down.

+5


source







All Articles