10

If I write

var a = [1,2];
var b = {
  foo: a.pop(),
  bar: a.pop()
};

What is the value of b, according to the specification?

(By experiment, it's {foo: 2, bar: 1}, but I worry whether this is implementation-specific.)

jameshfisher
  • 34,029
  • 31
  • 121
  • 167
  • Why would it be implementation-specific? `pop` mutates the original array. – elclanrs Jul 03 '13 at 00:37
  • 1
    @elclanrs, I think what the question is getting at is whether the values of the properties of object `b` will always be evaluated in the order in which they are listed in the code. – go-oleg Jul 03 '13 at 00:42
  • Oh, I see... Now that's actually a good question, but while the order of properties in an object is trivial, the order of evaluation is not, so I'd say this is non-issue but I may be wrong... – elclanrs Jul 03 '13 at 00:43

2 Answers2

12

See ECMAScript section 11.1.5 defining how the ObjectLiteral production is parsed.

In particular:

PropertyNameAndValueList , PropertyName : AssignmentExpression is evaluated as follows:

  1. Evaluate PropertyNameAndValueList.

  2. Evaluate PropertyName.

  3. Evaluate AssignmentExpression.

...

Where (1) is a recursive definition.

This means the leftmost item in an object literal will get evaluated first, and so {foo: 2, bar: 1} is indeed spec-mandated.

hopper
  • 13,060
  • 7
  • 49
  • 53
bobince
  • 528,062
  • 107
  • 651
  • 834
1

They are evaluated in the order they are written.

user2540812
  • 212
  • 2
  • 2