9

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

3
  • Why would it be implementation-specific? pop mutates the original array. Commented Jul 3, 2013 at 0: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. Commented Jul 3, 2013 at 0: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... Commented Jul 3, 2013 at 0:43

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

They are evaluated in the order they are written.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.