Tutorial — Arrays

Arrays are native JavaScript objects. Create a new Array with the new operator:

// Create a new Array with zero length...
var  arr1 = new Array();

// Create a new Array with three slots (0-2)...
var  arr2 = new Array("Contact", 12, new Date());

// Note that Arrays can contain variant object types!
// In the second example, the Array contains a String, a Number and a Date.

Arrays Are Dynamic

You can create array slots dynamically by assigning to them. The array.length Property always represents the highest assigned slot, however lower slots that have never been assigned anything remain undefined:

// Create arr[0] and arr[1] when we create the Array...
var  arr = new Array("foo", "bar");

// Assign to slot[6]...
arr[6] = "zardoz";

// Array now has length of 7 (0-6)
// However, arr[2] through arr[5] are undefined

Arrays Slots are also Properties

Defined Array slots are also Properties of the object. For example, array[0] is also array['0']! (Note that you can't use array.0, because names may not start with a digit. You can still access the Property through the array notation, however.)

// new Array[0-2]...
var  PoohFolk = new Array("Poohbear", "Piglet", "Eyeore");

// Give our Array object a name Property...
PoohFolk.name = "Winnie And Friends";

piglet = PoohFolk[1]; // Array access–Ok
piglet = PoohFolk['1']; // Property access–Ok
piglet = PoohFolk.1; // Property access–ERROR!

// Compare the above with regular Property access...
arrayName = PoohFolk['name']; // Property access–Ok
arrayName = PoohFolk.name; // Property access–Ok

The distinction may seem subtle, however it makes a difference when iterating over an array. Your results depend on the iteration techique you use. If you index the Array from 0 to array.length-1, you cover all potential slots. Some of them may be undefined. If you use a for (x in obj) loop to iterate over the Properties, you cover only the defined slots.

// new Array[0-1]...
var  Colors = new Array("Red", "Orange");

Colors[7] = "Blue"; // now it's [0-1 & 7]

// Iterate all slots...
for (var ix=0; ix < Colors.length; ix++)
{
    // Some slots might be undefined...
    Print ("Color: ", Colors[ix]);
}

// Iterate over Properties...
for (var prop_name in Colors)
{
    // All slots are defined...
    Print ("Color: ", Colors[prop_name]);
}