javascriptnode.jsecma

What is the significance of double square brackets in javascript property names when initializing the object?


I'm currently looking at some code that was written a while ago, and I'm not sure why the following 2 statements are equal and for some reason I've chosen to do the first way.

const a = 'foo';
const b = { [[a]]: 'boo' } // This is in code
const c = { [a]: 'boo' } // ES6 way

They both seem to produce exactly the same result. I'm not sure if the first option was a valid option pre ES6, but when I tried on node 0.10 for example it didn't recognise either of them as valid statements. It would be helpful to know why double square brackets produce the same result.

Update:

After seeing comments/answer I tried to confirm if the expression within double square brackets is treated as an array, and it is indeed.

> const foo = 'foo'
undefined
> const boo = 'boo'
undefined
> const combo = { [foo,boo]: 'foo boo' }
const combo = { [foo,boo]: 'foo boo' } // This doesn't work foo,boo is not a valid expression 
                    ^

Uncaught SyntaxError: Unexpected token ','
> const combo = { [[foo,boo]]: 'foo boo' }
undefined
> combo
{ 'foo,boo': 'foo boo' } // Treats expression itself as array and `toString()` gets called on the array producing 'foo,boo' string


Solution

  • In ES6, [expression]: value is interpreted as follows:

    Respectively,

     given [ [a] ]: 'boo'
    
     evaluate [a]   => ['foo']
     String ['foo'] => 'foo'
     result         => {'foo': 'boo'}
    

    In other words, extra brackets are ignored.