DEV Community

Sobio Darlington
Sobio Darlington

Posted on

Why does this work in javascript?

I just bumped into this. Anyone have insight as to why this works?

const a = {b: 2}; 

console.log( a[['b']] );

// Result: 2
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

vkbr profile image
Vivek B

Index(es) needs to be string and JS will automatically convert anything used as object's index to a string. ['b'].toString() happens to be equal to 'b' (its same as ['b'].join(',')).

sobiodarlington profile image
Sobio Darlington

Looks like it.

pcrunn profile image
Alexander P. • Edited

not sure if that's related but [['b']] appears to be equal to 'b'