170

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

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

return:

Object {b: "d"}
Mark Amery
  • 143,130
  • 81
  • 406
  • 459
lcharbon
  • 3,030
  • 2
  • 16
  • 18

5 Answers5

256

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"
Christopher Peisert
  • 21,862
  • 3
  • 86
  • 117
Sean Vieira
  • 155,703
  • 32
  • 311
  • 293
  • 8
    So til ES2022, [ ] can be Array Literal Constructor, Property Accessor, Computed Property Names, Destructuring Assignment, Binding Element (https://stackoverflow.com/a/37691566/9182265). I doubt there's more. – Dogkiller87 Apr 19 '22 at 22:30
  • 3
    Yep... JavaScript is a bit of a mess nowadays to be honest. A case of too many cooks. – Jack_Hu Jun 30 '22 at 11:08
54

Really the use of [] gives an excellent way to use actual value of variable as key/property while creating JavaScript objects.

I'm pretty much statisfied with the above answer and I appreciate it as it allowed me to write this with a little example.

I've executed the code line by line on Node REPL (Node shell).

> var key = "fullName";     // Assignment
undefined
>
> var obj = {key: "Rishikesh Agrawani"}    // Here key's value will not be used
undefined
> obj     // Inappropriate, which we don't want
{ key: 'Rishikesh Agrawani' }
>
> // Let's fix
undefined
> var obj2 = {[key]: "Rishikesh Agrawani"}
undefined
> obj2
{ fullName: 'Rishikesh Agrawani' }
>
hygull
  • 8,464
  • 2
  • 43
  • 52
26
const animalSounds = {cat: 'meow', dog: 'bark'};

const animal = 'lion';

const sound = 'roar';

{...animalSounds, [animal]: sound};

The result will be

{cat: 'meow', dog: 'bark', lion: 'roar'};

teunbrand
  • 33,645
  • 4
  • 37
  • 63
Moni
  • 826
  • 10
  • 15
6

Also, only condition to use [] notation for accessing or assigning stuff in objects when we don't yet know what it's going to be until evaluation or runtime.

1

I want to make an object but I don't know the name of the key until runtime.

Back in the ES5 days:

var myObject = {};
myObject[key] = "bar";

Writing two lines of code is so painful... Ah, ES6 just came along:

var myObject = {[key]:"bar"};

If the value of key equals foo, then both approaches result in:

{foo : "bar"}
Dean P
  • 1,841
  • 23
  • 23