Search code examples
javascriptarraysabstract-data-type

Is the JavaScript array really of type map


In JavaScript you are able to place a variable or an object into an array in a various ways:

array.push(item)
array[2] = item;
array[somevariable] = item

the latter of the above example is what bothers me

say for instance that i have the following variable var somevariable = 'someString';

i would be able to place this into the array as an index (or key) if you wish.

This behavior is mostly seen in the Map interface suggesting that the array in JavaScript is not of the type List.

Another note is that the Array object in JavaScript also has a pop method which is seen in the Queue interface.

So my question is what data type is the Arrayin JavaScript?


Solution

  • Arrays are just objects with some special methods and behaviors.

    As objects, you can store properties in them. The key must be a string (or symbol in ES6), and the value can be anything.

    However, array methods only take into account the properties whose names are array indices.

    15.4 Array Objects

    Array objects give special treatment to a certain class of property names. A property name P (in the form of a String value) is an array index if and only if ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal to 232−1.

    It's recommended to use only array indices in arrays. If you want other properties, you won't be able to use array methods with them. But then better use a normal object. Or maybe a ES6 map, whose keys and values can be anything.

    The spec doesn't say how arrays should be implemented. Most implementations use some kind of list in case there are only array indices, but switch to a hash if you add other properties.