var a = [5, 88, 21]; //Constructs an array with three elements
a[2] //Returns 21
a.length //Returns 3
a[a.length - 1] //Returns 21
Observe that the last of the above expressions will a lways return th e last element of
the a array regard le ss of its size.
Incidenta lly, it is no t imperative that an arra y contains elements with contiguous in-
dexes starting at zero. If some elements are missing in between, then we say that the
array is sparse. The value of the length property of a sparse array is not equ al to the
number of elements but simply one greater than the index of the last ele ment:
var a = []; //Constructs an empty array
a[5] = 42; //Adds an element to the array and sets its value to 42
a.length //Returns 6
In the above example, I constructed an empty array and then dynamically added the
sixth element to it. The elements a[0] to a[4] do not exist, although some of older
browsers wrongly set them to undefin ed. In practice, however, you will rarely use
sparse arra ys, so I will not go any deeper into the subject.
Mike: I’m just curious: is there any connection between square brac kets used for
accessing a prope rty of an object an d square brac kets used for accessing an element?
Professor: Both work the same . Recall that a property name within brackets should
be a string. Of co urse, JavaScript doesn’t min d at all if you p rovide a numeric in-
dex instead of a string. It simply converts the numeric value to a string according to
the general type-conversion rules. For example, the index 0 becomes the string "0",
which is then used as a property name. In that sense, all indexes are no more than
property names.
That said, there are two fundamental differences between an arr ay index an d an ordi-
nary object property name. You should, of course, first be able to clearly distinguish
an arr ay index from an object property name. Any property n ame that is an integer
between zero and 2
32
− 2 is an array index. For exam ple, 3 or 42 are ar ray indexes but
-5 or 1.4 are regular object properties with names "-5" and "1.4", respectively.
Maria: Does that mean that any object typ e can have indexes?
Professor: No, of course not. Indexes as such only apply to ar ray objects. If you
use property names 3 or 42 with a date object, for example, they will behave just like
ordinary properties, and not like true indexes.
Mike: Are you saying that we can add our own properties to an existing object?
Professor: That’s right, but let’s leave that topic for our next meeting.
If you therefore use an integer b etween zero and 2
32
− 2 as an array p roperty name, it
will behave like a tr ue index. The first differe nce in usin g an index rather than a regular
172 Meeting 9. Understanding Arrays and Strings