3

I'm failing to find documentation as to how/why the following works:

const data = {one: 1, two: 2}
const key = ['one']

data[key[0]] // 1
data[key] // 1
data[[key]] // 1  
data[[[key]]] // 1
data[[[[key]]]] // 1
data[['one', 'two']] // undefined

What allows any number of square brackets to surround the key and still successfully find the key in the object? Is there specific behavior when array.length === 1? And if so, where can I find documentation or clarity on that?

Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
Andy Bas
  • 217
  • 1
  • 4
  • 11
  • It's documented in [`Array#toString()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toString) – 4castle Aug 26 '16 at 19:53
  • Just FYI, this behavior is not specific to ES 6. It would work the same if you replaced `const` with `var`. – Michał Perłakowski Aug 26 '16 at 19:55

2 Answers2

4

When using the object[key] bracket notation to access properties, the key is converted to a string.* The string representation of an array is the string representations of its elements joined with ,. For a one-element array, that's the same as the string representation of its only element.

const foo = {'a,b': 2};
console.log(foo[['a', 'b']]); // 2;

* Or a symbol.

Ry-
  • 218,210
  • 55
  • 464
  • 476
1

When you access a property using square brackets, the key is always converted to string. And if you convert an array to string, the result is the same as calling the join() method on the array. Therefore, converting to string an array, which contains only one element, which is a string results in that element itself. However, when array contains two string elements (like ['one', 'two']), converting it to string results in 'one,two', and the data variable doesn't contain that key.

Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177