Arrays in JavaScript are mutable lists with a few built-in methods. You can define arrays using the array literal:
var x = []; var y = [1, 2, 3];
The type of an array is "object":
typeof []; // "object" typeof [1, 2, 3]; // "object"
Reading and writing elements to an array uses the array-notation:
x[0] = 1; y[2] // 3
Iteration
An array has a length property that is useful for iteration:
for (var i = 0; i < a.length; i++) {
// Do something with a[i]
}
When performance is critical, reading the length property only once can help to speed things up. This should be used only when a performance bottleneck was discovered:
for (var i = 0, j = a.length; i < j; i++) {
// Do something with a[i]
}
Another variation defines a variable that is filled for each iteration, removing the array-notation from the loop-body. It does not work when the array contains 0 or empty strings!
for (var i = 0, item; item = a[i]; i++) {
// Do something with item
}
jQuery provides a generic each-function to iterate over element of arrays, as well as properties of objects:
var x = [1, 2, 3];
jQuery.each(x, function(index, value) {
console.log("index", index, "value", value);
});
The drawback is that the callback is called in the context of each value, therefore you lose the context of your own object if applicable. More on this below at Functions.
The length property can also be used to add elements to the end of an array. That is equivalent to using the push-method:
var x = []; x.push(1); x[x.length] = 2; x // 1, 2
You'll see both variations a lot when looking through JavaScript library code.
Other built-in methods are reverse, join, shift, unshift, pop, slice, splice and sort:
var x = [0, 3, 1, 2];
x.reverse() // [2, 1, 3, 0]
x.join(" – ") // "2 - 1 - 3 - 0"
x.pop() // [2, 1, 3]
x.unshift(-1) // [-1, 2, 1, 3]
x.shift() // [2, 1, 3]
x.sort() // [1, 2, 3]
x.splice(1, 2) // [2, 3]
Note: .unshift() method does not return a length property in Internet Explorer.
Boolean Default
An array, no matter if it has elements or not, never defaults to false:
![] // false
Array<Type> Notation
In the jQuery API you'll often find the notation of Array<Type>:
dragPrevention Array<String>
This indicates that the method doesn't only expect an array as the argument, but also specifies the expected type. The notation is borrowed from Java 5's generics notation (or C++ templates).

