lcharbon
lcharbon

Reputation: 3298

What do square brackets (`[ (…) ]`) do inside an object literal in the position of an object key?

Can anyone explain how the below method of assigning keys in JavaScript works?

let a = "b"
let c = {[a]: "d"}

console.log(c)  // Object {b: "d"}

Upvotes: 178

Views: 67024

Answers (1)

Sean Vieira
Sean Vieira

Reputation: 159875

It's the new ES2015 (the EcmaScript spec formally known as ES6) computed property name syntax. It's a shorthand for the someObject[someKey] assignment that you know from ES3/5:

var a = "b"
var c = {[a]: "d"}

is syntactic sugar for:

var a = "b"
var c = {}
c[a] = "d"

Upvotes: 261

Related Questions