Associative arrays: A mechanism that shares a lot of superficial similarity to the array is the associative array or hash, which in JavaScript is actually a class of object rather different than real arrays in that they can be indexed by non-numeric objects (like strings)

C=new Array; C[“ham”]=”eggs”; C[4]=document
(note: C=[]; is equivalent to C=new Array;)

The above is equivlant to

C={“ham”:”eggs”,4:document}

in which the resemblance to objects becomes more obvious.  It is also, perhaps surprisingly, the same as

C=new String; C[“ham”]=”eggs”; C[4]=document

This is because strings and arrays in JavaScript are both objects and because, objects, like hashes in other languages, may have properties of any sort assigned to them. In JavaScript A[“a”] is notationally equivalent to A.a, which provides convenience in referring to arbitrary properties of objects, but also promotes a bit of confusion about the difference between “true” arrays and associative ones in the language.

To avoid the confusion with specialized objects which may have no particular relevance to the associative array one wished to define, it may be best to use the notation

C=new Object; C[“ham”]=”eggs”; C[4]=document
(note: C={}; is equivalent to C=new Object;)

Associative arrays differ from ordinary consecutive numeric arrays in that length returns only the value of the highest numerical index. Likewise array operators like join and pop will work only with the portion of the hash that is numerically indexed, returning results which may be confusing at times.

Another approach for building associative arrays involves the use of an object constructor function. Though a bit cumbersome for this purpose, it may illustrate some of the richness of the language and will be discussed later under objects:

A=new Klingon(5,”hi”,3)

in which the function Klingon creates new objects based on its array of incoming arguments.

function Klingon(){
    for (i=0;i<arguments.length;i++) this[i]=arguments[i]
}

The above creates an object quite similar to B=[5,”hi”,3] in that a pairwise comparison of their elements will suggest identity, though array methods and properties such as length and pop are unavailable to this associative object.