Search code examples
javascriptjavascript-objects

Why does JavaScript allow accessing an object's property using an array of length 1, as if the array was just the single element itself?


See this example:

> map = { 5: 'five' }
> map[5] 
'five' // Makes sense
> arr = [5]
> map[arr]
'five' // Does not make sense
> arr = [5,6,7]
> map[arr]
undefined // I'm cool with that

So when I access an object's property with an array of length 1, it behaves as if I simply input the single element instead of the array. But when the array's length is anything but 1, it will produce the expected behavior.

What is the purpose of this behavior? To me this would simply make things harder for a developer to find a bug in their code.


Solution

  • If an object index is not a string or Symbol, it's converted to a string as if by its toString() method.

    array.toString() performs the equivalent array.join(",").

    So

    map[arr]
    

    is equivalent to

    map[arr.join(",")]
    

    If the array has one element, joining it simply returns that one element converted to a string, so it's equivalent to

    map[arr[0].toString()]
    

    and that explains your first result.

    But in your second example, it returns the string "5,6,7" and there's no property with that name in the object.