1

code:

const x = 6;
const ob = {x: [6.1, 6.5]} 
console.log(ob) // {x: [6.1, 6.5]}

const y = 6;
const ob = {[y] : [6.1, 6.5]};
console.log(ob) // {6: [6.1, 6.5]}

Why square brackets allow use the value of the variable as object key, is this related to destructuring??

Saher Elgendy
  • 981
  • 1
  • 10
  • 20
  • 1
    It's a special type of syntax known as computed property names. See: [What do square brackets around a property name in an object literal mean?](https://stackoverflow.com/q/34831262) – Nick Parsons Jul 07 '20 at 03:46
  • 1
    thanks for that info, – Saher Elgendy Jul 07 '20 at 03:47
  • 2
    It's not related to destructuring. In your first example, the two "x"s have nothing to do with each other (the `const x` line is unused). The syntax `ob["foo"]` is the same as `ob.foo`, but you can only use the latter syntax because "foo" is a valid identifier. You could use `ob["foo-bar"]` but not `ob.foo-bar`. The bracket syntax also allows you to use a property where you don't know the key at compile time, eg `const key = calculateKey();ob[key]` – user2740650 Jul 07 '20 at 03:52

2 Answers2

1

The square brackets allow for computed property keys. In other words, the value of the variable inside of the square brackets is processed before the value is accessed.

kenput3r
  • 184
  • 1
  • 9
1

Its called Computed Property Names, its implemented using bracket notation(square brackets) []

Example: { [variableName] : someValue }

For ES5, try something like this

var yourObject = {};

yourObject[yourKey] = "yourValue";

console.log(yourObject );

Example:

var person = {};
var key = "name";

person[key] /* this is same as person.name */ = "John";

console.log(person); // should print  Object { name="John"}
Omar
  • 648
  • 7
  • 11