Arrays:

Arrays are like a folder of data items. Like strings, data items within an array are indexed starting at 0. Like strings if there is no data at a specific index, then the result is "undefined". Unlike strings, arrays may hold any kind of data at each location and may even have "holes" in the array.

Arrays are created using square brackets:

var a = [ 1, 2, 3 ]; // An array holding three numbers. var a2 = [ 1, 2, "three", , "five" ]; // An array with numbers and strings and nothing at index 3.

Useful properties and methods

.length - Gives the length of array (or highest index + 1).

.join(separator) - method to join items in the array together with the string passed to join (separator) between each element.

a.join(" "); // outputs "1 2 3" a.join(","); // outputs "1,2,3" a.join(""); // outputs "123"

.reverse() - Reverses elements in an array.

"abc".split("").reverse().join(""); // returns "cba"

Methods can be chained together. The above splits the string "abc" into an array ['a', 'b', 'c'], then reverses it to ['c', 'b', 'a'] then joins the elements together into 'cba'.

Multi-dimensional arrays:

One can have arrays inside of arrays, like:

var m = [[1,2,3],[4,5,6],[7,8,9]]; // A 2-dimensional array

To access an element you can chain the indexes, they are read from left to right, i.e.:

m[i][j] where:
i = index into the primary array.
j = index into the sub-array.

Example:

m[0][2] == 3; m[1][0] == 4;

Other useful array properties and methods

.push(value) - Adds value to the end of the array. Example:

var a = []; a.push(3); a.push(2); a.push(1); // a == [3, 2, 1]

.pop() - Removes the last element from an array and returns it. Example:

var data = a.pop(); // data == 1; a == [3, 2]

.unshift(value) - Adds value to the beginning of an array. Example:

a.unshift(2); a.unshift(1); // a == [1, 2, 3, 2];

.shift() - Removes the first element from an array and returns it. Example:

var data = a.shift(); // data == 1; a == [2, 3, 2];

.indexOf(value) - Returns the first index of an element matching value or -1 if not found. Example:

a.indexOf(2) === 0;

.forEach(func) - Calls the function func for each individual element in the array, passing the function the value of the element. Example:

// Print out all the elements of the array a: a.forEach(function (val) { console.log(val); });