2

I'd 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 attribute values will be evaluated in the same order that I write them. Does the language make such a guarantee anywhere?

1 Answers1

5

From ECMA 3rd Edition specifications:

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

In other words, yes, the specification 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 does NOT have to do with the order of attributes as they are stored in an object, but rather, the order in which JavaScript will evaluate your statement: left-to-right, up-to-down.

Chris Nielsen
  • 14,731
  • 7
  • 48
  • 54
  • hmm. I could have sworn that g Chrome failed to maintain this ordering last time I tried this. Other browsers were more predictable, but in Chrome I needed a client side sort to restore order. – spender Sep 10 '09 at 02:12
  • The question isn't about the order of attributes in the object AFTER the code has run. The question is about the order of execution that will be applied to each term as the object is created. If your Chrome is executing your code from right-to-left, there are bigger issues afoot. – Chris Nielsen Sep 10 '09 at 02:13
  • Chris is correct. I'm asking whether Javascript reserves the right to evaluate the values of the object literal in an unpredictable order, like the "let" form in Lisp, or whether it will always evaluate them in the order I wrote them in, like the "let*" form. –  Sep 10 '09 at 02:27
  • The specification text only states how the raw text of the program is processed into "input elements". This particular text says noting about what order the collected input elements are processed. – Ira Baxter Sep 10 '09 at 03:24
  • The "longest possible sequence of characters as the next input element" applies to lexical analysis, which happens WAY before the code is executed. That statement has nothing to do with when the components are evaluated at runtime. If JavaScript does guarantee an order, that guarantee will be listed somewhere else in the spec. See http://stackoverflow.com/a/17438220/831878 for the correct answer. – Ray Toal Dec 31 '15 at 01:27