4

That question title was a mouthful, and this is very difficult to explain without an example:

Given a variable:

const string = 'test';

An object can be created where the variable is passed in as a property value without explicitly defining a property name:

const obj = { string };

Which results in the variable's name being used as the property name, and the variable's value being used as the property value:

{
    string: 'test'
}

I'm wondering if there is a name for this feature, or if this is documented somewhere as expected behaviour? Is this something that is a part of a specific JS language version? (In other words, is this something that all browsers will support?)

My first thought was that it had some relation to destructuring assignment, as a similar syntax exists there for something like:

const { a, b } = { a: 'Letter A', b: 'Letter B' };

But that's not quite the same thing, so I don't know if that idea holds any merit.

I want to make sure I understand this language feature before I use it (or decide if I should use it, if it's perhaps less of a feature and more of a thing that just happens but shouldn't be relied upon ;) )

Blake Mann
  • 5,440
  • 23
  • 37
  • 2
    They're commonly called shorthand property names. [Documentation for them can be found here.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#New_notations_in_ECMAScript_2015) – CRice Nov 02 '18 at 19:00
  • 1
    For *why* it has it - because VERY often you'd be writing stuff like `newObj = {id: id, name: name}`, etc. when constructing and returning objects and similarly, when receiving them, you'd often have to do `obj = getObj(); id = obj.id; name = obj.name;`. So this was codified and syntactic sugar was added to avoid some of this boilerplate. And for *how* - well, after it was codified in a proposal, and then accepted, it was implemented as part of the language. – VLAZ Nov 02 '18 at 19:08

0 Answers0