Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does JS allow property access with an array as key?

Suppose I have an object

obj = {
  a : 1
}

I'm able to access property a via obj["a"] but I'm also able to access it via obj[["a"]]. How is that possible?

like image 886
yogupta Avatar asked Nov 16 '19 12:11

yogupta


People also ask

Can an array be a key in JavaScript?

On each iteration, we assign the array value as a key in the object and return the new value of the accumulator variable. We initialized each key to an empty string, however you can assign whatever value suits your use case. The object will contain all of the array's elements as keys after the last iteration.

How do you access properties in an array?

So if you want to access a property named 2 or John Doe, you must use square brackets: value[2] or value["John Doe"] . The elements in an array are stored as the array's properties, using numbers as property names.

Can a property be an array?

Array properties also exist. These are properties that accept an index, just as an array does. The index can be one-dimensional, or multi-dimensional. In difference with normal (static or dynamic) arrays, the index of an array property doesn't have to be an ordinal type, but can be any type.

Are properties and keys the same in JavaScript?

Properties are made up of key : value pairs. We may see the term property used to indicate a key, but on the whole we may think of a property as having both a name and a value. This of course differs from key, since key is just a name.


1 Answers

Object keys are always strings (or, rarely, symbols). When you do

obj[<expression>]

the interpreter will try to turn expression into a valid key, if it isn't one already. In this case, turning ["a"] into a string results in "a", so both obj["a"] and obj[["a"]] work.

(When an array is implicitly turned into a primitive, like here, it gets .joined by a comma, and ["a"].join(',') === "a")

like image 145
CertainPerformance Avatar answered Sep 22 '22 04:09

CertainPerformance