tags:

views:

64

answers:

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?

A: 

You going to expect this to work in browsers?

They don't implement the same language exactly... It wouldn't matter if it was written down somewhere how it should be, the fact is the browsers are different. Decide what browsers you want your code to work on, then test it on those.

If you don't have access to them all, you can make a simple page that graphically displays which result the browser is getting, then submit that page to browsershots.org

JasonWoof
You're thinking of DOM API implementations, which vary (sometimes wildly) across browser vendors. JavaScript (i.e. the dialect of ECMAScript) is very consistent across implementations.
Crescent Fresh
+3  A: 

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
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
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
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.
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