0

Consider the following example

var x = 1;
var obj = {y:1, x};
console.log(obj, obj.x);

I have tried to find many stackoverflow posts and MDN documentations, but I fail to find any reference that says we can use variables as object keys without the ES6 array syntax. That is, I assume js allows var x=1; var obj2 = {y:1, [x]: 3}.

Is there some sort of object destructuring happening? Why can I use a variable as property name in the object literal creation without even assigning that property a value?

user31782
  • 7,087
  • 14
  • 68
  • 143
  • 3
    `{x}` is shorthand for `{x:x}` - as clearly [documented](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#property_definitions) - it's been around for over 7 years on all browsers :p – Jaromanda X Sep 27 '22 at 01:35
  • @JaromandaX I have been living under a stone for 7 years :-D never came across this notation. – user31782 Sep 27 '22 at 01:41

0 Answers0