Introduction

Arrays are a dead handy language feature in Javascript. They are simply a list of things, of any type. They are similar to objects, which we cam across last week, but they don’t have named keys. Instead they are indexed; each thing in the array is numbered, starting from zero.

An example of some arrays are:

var someStrings = ["This string", "That string", "The other string"];
var someNumbers = [15, 9128476, 2442, 30, 463, 123, -10, 24, 56, 41, 52, 34, 64, 12];
var aMixedListOfStuff = [
    "a string",
    ["nested", "array", "of", "strings"],
    123,
    {wow: "An object!"},
    function() {
        return "What is this!? A FUNCTION! IN an ARRAY! Madness!"
    }
];

As you can see from the examples, an array in Javascript can be a list of anything of any type. Even mixed types. It is unusual to mix types though, and is usually best avoided. Arrays are most powerful when they contain a list of similar things that you can perform the same operation on repeatedly.

The language gives you a few handy features with an array. Firstly, you can always read its length using .length. For example:

someStrings.length; // is 3
someNumbers.length; // is 14
aMixedListOfStuff.length; // is 5

You can always access an element by its index as well, and you do this using square brackets like this:

someStrings[0]; // is "This string" because array indexing starts at zero.
someStrings[2]; // is "The other string"
someNumbers[5]; // 123
aMixedListOfStuff[0]; // "a string"
aMixedListOfStuff[1]; // ["nested", "array", "of", "strings"]
aMixedListOfStuff[1][3]; // "strings" - get the element at index 3 from the array at index 1

As well as these builtins, you can use various standard methods for accessing and using arrays. Some of the commonest are push(), pop(), unshift() and shift(). Other handy ones are forEach(), some() and indexOf(). You can find a big list of these at the MDN page on arrays and you should go read that page.

A more in depth example

So, putting it all together, here’s a “real world”(ish) example of using an array in a bit of code managing a shopping basket.

function getTotal(items) {
    // start the total as zero
    var total = 0;

    // first check we actually have an array
    if (!(items instanceof Array)) {
        throw new Error("getTotal requires an array. " + typeof(items) + " given instead.");
    }

    // Now loop through the array items.
    items.forEach(function(item, index) {
        if (typeof(item.cost) !== 'number' || typeof(item.qty) !== 'number') {
            // Make sure each item is a valid item.
            throw new Error("getTotal requires an array of valid items. Item " + index + " appears to be invalid.");
        }

        // Add the cost onto the total for each item.
        total += (item.cost * item.qty);
    });

    return total;
}

In this example, we’d pass in something like this:

var basketItems = [
    {desc: "Electric pencil sharpener", qty: 1, cost: 10.00},
    {desc: "HB Pencil", qty: 10, cost: 0.50},
    {desc: "2B Pencil", qty: 2, cost: 1.00},
    {desc: "Pencil Eraser", qty: 2, cost: 1.50}
];

var total = getTotal(basketItems); // total returned is 20.00

The array os passed into the function which loops over all the items and extracts the information it needs from each one, incresing the total as it goes. (The objects in the array can contain any extra keys, so long as the qty and cost are always numbers. In this example desc is just ignored by the function.)