Tuesday, 13 April 2021

Why does array allow string as an index in JavaScript

As we already know one of the differences between array and object is:

"If you want to supply specific keys, the only choice is an object. If you don't care about the keys, an array it is" (Read more here)

Besides, according to MDN's docs says that

Arrays cannot use strings as element indexes (as in an associative array) but must use integers

However, I was so surprised that

var array = ["hello"]; // Key is numeric index
array["hi"] = "weird"; // Key is string
>> content structure looks like:  ["hello", hi: "weird"]

The content structure of the array looks so weird. Even more, when I check the type of array it returns true

Array.isArray(array) // true

Question:

  1. Why have this behavior? This seems inconsistent, right?
  2. What is the data structure actually storing behind the scene: as an array or something like object, hashtable, linkedlist?
  3. Whether this behavior depends on a specific Javascript Engine (V8, SpiderMonkey, etc..) or not?
  4. Should I use array like this(keys are both numeric index and string) over normal object?


from Why does array allow string as an index in JavaScript

No comments:

Post a Comment