Saher Elgendy
Saher Elgendy

Reputation: 1619

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

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

Upvotes: 6

Views: 1459

Answers (1)

kenput3r
kenput3r

Reputation: 249

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.

Upvotes: 4

Related Questions