Can anyone explain how the why/how the below method of assigning keys in JavaScript works?
JavaScript
x
3
1
a = "b"
2
c = {[a]: "d"}
3
return:
JavaScript
1
2
1
Object {b: "d"}
2
Advertisement
Answer
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:
JavaScript
1
3
1
var a = "b"
2
var c = {[a]: "d"}
3
is syntactic sugar for:
JavaScript
1
4
1
var a = "b"
2
var c = {}
3
c[a] = "d"
4