Why square brackets allow use of variable value as object key?

Viewed 391

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??

2 Answers

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.

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"}
Related