DEV Community

Why does this work in javascript?

Sobio Darlington on September 12, 2019

I just bumped into this. Anyone have insight as to why this works? const a = {b: 2}; console.log( a[['b']] ); // Result: 2 Enter fulls...
Collapse
 
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(',')).

Collapse
 
sobiodarlington profile image
Sobio Darlington

Looks like it.

Collapse
 
pcrunn profile image
Alexander P. • Edited

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