Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript object initialization and evaluation order [duplicate]

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

like image 661
jameshfisher Avatar asked Jul 03 '13 00:07

jameshfisher


People also ask

Which of these is the correct way to initialize an object variable in JavaScript?

Objects can be initialized using new Object() , Object. create() , or using the literal notation (initializer notation). An object initializer is a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ( {} ).

Does object keys guarantee order?

You can indeed access the object keys as an iterable object using the Object. keys() method, which lets you use a for...of loop, but the order of the resulting object keys is not guaranteed. The behavior is the same for Object. values() or Object.

Does object keys Return same order?

The Object.keys() method returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would.


1 Answers

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.

like image 98
bobince Avatar answered Oct 03 '22 00:10

bobince