var obj = { type: 'data', x, y, data: []}
Obviously this was my typo, {x,y}
should have been {x:x, y:y}. But it does what I want, in Chrome, field x
gets the value of a local variable x
.
But why does it work?
var obj = { type: 'data', x, y, data: []}
Obviously this was my typo, {x,y}
should have been {x:x, y:y}. But it does what I want, in Chrome, field x
gets the value of a local variable x
.
But why does it work?
Share Improve this question edited Jun 16, 2015 at 19:30 thefourtheye 240k53 gold badges465 silver badges500 bronze badges asked Jun 16, 2015 at 19:08 exebookexebook 34.1k42 gold badges152 silver badges241 bronze badges 1- Version 43.0.2357.81 Built on Ubuntu 14.04, running on LinuxMint 17.1 (64-bit) – exebook Commented Jun 16, 2015 at 19:12
2 Answers
Reset to default 11It is part of the ECMAScript 2015 (or ECMAScript 6). You can create new properties in Objects in Object literals, just by specifying the identifiers.
Quoting MDN's Object Initializer's Property Definitions section,
With ECMAScript 6, there is a shorter notation available to achieve the same:
var a = "foo", b = 42, c = {}; // Shorthand property names (ES6) var o = { a, b, c };
The corresponding section in ECMAScript 6 specification is here,
AssignmentProperty : IdentifierReference Initializeropt
- Let P be StringValue of IdentifierReference.
- Let lref be ResolveBinding(P).
- ReturnIfAbrupt(P).
- Let v be GetV(value, P).
- ReturnIfAbrupt(v).
- If Initializeropt is present and v is undefined, then
- Let defaultValue be the result of evaluating Initializer.
- Let v be GetValue(defaultValue).
- ReturnIfAbrupt(v).
- If IsAnonymousFunctionDefinition(Initializer) is true, then
- Let hasNameProperty be HasOwnProperty(v, "name").
- ReturnIfAbrupt(hasNameProperty).
- If hasNameProperty is false, perform SetFunctionName(v, P).
- Return PutValue(lref,v).
Basically, the specification says that, if you are using just an identifier, a new property with the name of the identifier will be created, and the value will be the actual value of that identifier. It can even be a name of the function.
var a = "foo", b = 42, c = {}, d = function () {};
console.log({a, b, c, d});
// { a: 'foo', b: 42, c: {}, d: [Function] }
ES2015 has enhanced object literal notation. Chrome 43ish supports this (partially).
Babel has a good explanation.