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.)
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 ( {} ).
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.
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.
See ECMAScript section 11.1.5 defining how the ObjectLiteral
production is parsed.
In particular:
PropertyNameAndValueList
,PropertyName
:AssignmentExpression
is evaluated as follows:
Evaluate PropertyNameAndValueList.
Evaluate PropertyName.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With