HTML Dog
Skip to navigation

Arrays

Arrays are lists of any kind of data, including other arrays. Each item in the array has an index — a number — which can be used to retrieve an element from the array.

The indices start at 0; that is, the first element in the array has the index 0, and subsequent elements have incrementally increasing indices, so the last element in the array has an index one less than the length of the array.

In JavaScript, you create an array using the array-literal syntax:


var emptyArray = [];

var shoppingList = ['Milk', 'Bread', 'Beans'];

You retrieve a specific element from an array using square bracket syntax:


shoppingList[0];

Milk

It’s also possible to set the value at a particular index, again using the square bracket syntax:


shoppingList[1] = 'Cookies';

// shoppingList is now ['Milk', 'Cookies', 'Beans']

You can find the number of elements in the array using its length property:


shoppingList.length;

3

You can use push and pop methods to add and remove elements from the end of the array:


shoppingList.push('A new car');

// shoppingList is now ['Milk', 'Bread', 'Beans', 'A new car']

shoppingList.pop();

// shoppingList is back to ['Milk', 'Bread', 'Beans']

Here’s an example that creates, pushes, pops and iterates over an array, passing each name to a function called helloFrom. helloFrom returns a string with a greeting: “Hello from ” and then the person’s name. After the pushing and popping, the final list of people is: “Tom”, “Yoda”, “Ron” and “Bob”.


var helloFrom = function (personName) {
    return "Hello from " + personName;
}

var people = ['Tom', 'Yoda', 'Ron'];

people.push('Bob');
people.push('Dr Evil');

people.pop();

for (var i=0; i < people.length; i++) {
    var greeting = helloFrom(people[i]);
    alert(greeting);
}