'Square Brackets Javascript Object Key

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


Solution 1:[1]

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' }
>

Solution 2:[2]

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'};

Solution 3:[3]

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.

Solution 4:[4]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 hygull
Solution 2 teunbrand
Solution 3 Eldiyar Talantbek
Solution 4 Dean P