Why / how does JavaScript allow an object's property name to be set by the variable name when providing a variable value with no property name?

Viewed 35

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

0 Answers
Related