Search code examples
javascriptsemantics

Javascript object initialization and evaluation order


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


Solution

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