Like most languages, JavaScript lets you create arrays to store bunches of values in. An array is simply a sequence, or list, of values. A value in a JavaScript array can be anything from a number or string, through to a function or an object; JavaScript arrays can store pretty much any type of data. A single value in a JavaScript array is called an element.
With JavaScript arrays, you can:
- Store any number of values, including no values at all (known as an empty array)
- Access any or all the elements of an array through a single variable name
- Read and write elements of an array
- Loop through all the elements of an array
- Join two or more arrays together to make one longer array
- Convert an array to one long string
- Add or remove elements from the beginning, end, or middle of an array
- Reverse the order of the elements in an array
- Sort the elements of an array in any order you like
- Nest arrays within other arrays
JavaScript stores arrays as Array
objects, so most of the things you can do with arrays revolve around the properties and methods of the Array
class.
In this introductory article, you look at creating arrays, accessing the contents of arrays, the concept of array lengths, and looping through arrays.
Creating a JavaScript array
There are many ways to create a JavaScript array. For example, you can use an array literal, as follows:
// Create an empty array
var emptyArray = [ ];
// Create an array of fruit
var fruits = [ "apple", "pear", "orange", "banana" ];
You can also create a new Array
object:
// Create an empty array
var emptyArray = new Array ( );
// Create an empty array that's 15 elements long
var emptyElementsArray = new Array ( 15 );
// Create an array of 1 element
var myName = new Array ( "Matt" );
// Create an array of fruit
var fruits = new Array ( "apple", "pear", "orange", "banana" );
You’re not limited to passing literal values to the Array
constructor. For example, you can create an array containing the values of some variables:
var favouriteFruit = "banana";
var favouriteColour = "red";
var favouriteNumber = 8;
var favourites = new Array ( favouriteFruit, favouriteColour, favouriteNumber );
The above code produces the following array:
[ "banana", "red", 8 ]
You can even create arrays of functions and objects. For example, the following (rather pointless) array contains the DOM window
object, the DOM document
object, and the String.unescape()
function:
var randomStuff = new Array ( window, document, unescape );
Accessing the contents of an array
Each element in an array is given an index, which is an integer value between 0 and one less than the length of the array. The first element has an index of 0, the second element has an index of 1, and so on.
To access an element, use the syntax:
arrayName[index]
For example, using our favourites
array that we created above:
alert ( favourites[0] );
alert ( favourites[2] );
…produces 2 alert boxes with the values banana and 8 respectively.
As well as reading array elements, you can also write to array elements in a similar fashion. For example:
favourites[0] = "apple";
…changes the first element of the favourites
array from “banana” to “apple”.
Understanding array lengths
To retrieve the length of an array, use its length
property, as follows:
var fruits = new Array ( "apple", "pear", "orange", "banana" );
alert ( fruits.length ); // Displays "4"
The length of an array isn’t necessarily the same as the number of elements in an array. For example, the following array has a length of 15, but it only contains a single element:
var myArray = new Array ( 15 );
myArray[0] = "myValue";
You can also set an array’s length at any time:
myArray.length = 50;
- If you set an array’s length to be greater than its current length, no new elements are created; the array merely ends up with a longer
length
property. - If you set an array’s length to be less than its existing length, you shorten the array’s
length
property. In addition, any elements with indices that fall outside the new array length are discarded.
You can also increase the length of an array by adding a new element with an index greater than or equal to the array’s current length. The example below changes myArray
‘s length from 15 to 100:
myArray[99] = "anotherValue";
If you set an array to be a certain length, all values within the array that have not been explicitly defined have the value undefined
. So in the above example, myArray[0]
contains “myValue”, and myArray[1] – myArray[99]
all contain the value undefined
.
Looping through arrays
One of the most useful things about a JavaScript array is that you can use a loop to move through each element of the array in turn. Consider this non-looping example, which displays each of the six fruits in the fruits
array in turn:
var fruits = new Array ( "apple", "pear", "orange", "banana", "peach", "strawberry" );
alert ( fruits[0] ); // Displays "apple"
alert ( fruits[1] ); // Displays "pear"
alert ( fruits[2] ); // Displays "orange"
alert ( fruits[3] ); // Displays "banana"
alert ( fruits[4] ); // Displays "peach"
alert ( fruits[5] ); // Displays "strawberry"
As you can imagine, this starts to become unwieldy when you have a lot of elements in your array.
Here’s how to do the same thing with a for
loop:
var fruits = new Array ( "apple", "pear", "orange", "banana", "peach", "strawberry" );
for ( i=0; i < fruits.length; i++ )
{
alert ( fruits[i] );
}
Not only is the loop version more compact, but you can use it to handle any number of array elements without needing to change the code.
Further reading
Now that you know the basics of JavaScript arrays, take a look at Manipulating JavaScript arrays, which explains how to extract portions of an array; how to join arrays together; how to convert an array to a string; and how to add and remove elements from an array.
The Mozilla Developer Center has a good reference covering the Array
class. W3Schools also summarizes Array
‘s methods and properties and provides some handy examples that you can try out.
This is an optimization of the loop:
for(var i=0, len=myArray.length; i < len; i++){}
as the length is “cached” and not recalculated every time.
If you want to know more details about this topic, read my post http://bit.ly/arrayjs
In the Array length section it states:
“myArray[99] = “anotherValue”;
If you set an array to be a certain length, all values within the array that have not been explicitly defined have the value undefined. So in the above example, myArray[0] contains “myValue”, and myArray[1] – myArray[99] all contain the value undefined.”
Surely myArray[99] should be “anotherValue”, not undefined, or am i mistaken?
Regards,
Clive
please help me with this
an array of products can be set up as below for use on an ecommerce web site.
var products = [“Printer”,”Tablet”,”Router”];
Set up an array to include the items shown above, plus a few extras of your choice.
Write a script that:
outputs the items in alphabetical order
counts the number of items in the array
Mod Edit;
Replies are done in the forum so every body can benefit.
[Edited by chrishirst on 22-Nov-16 15:25]
Count items;
http://www.w3schools.com/jsref/jsref_length_array.asp
sort array;
http://www.w3schools.com/jsref/jsref_sort.asp
All array methods and properties;
http://www.w3schools.com/jsref/jsref_obj_array.asp