- Arrays — lists of numbers, strings, booleans, or any other data type.
- Array access — each item in the array can be accessed by its numeric index.
var products = ['soccer ball', 'cleats', 'socks', 'shorts'];
console.log(products); // 'soccer ball'
console.log(products); // 'shorts'
In the example above, the variable
products is an array of four strings. The array is created using bracket (
) notation. Each array item is separated by a comma. On line 2, the first array item (
'soccer ball') is accessed using its position in the array (
0) and logged to the console. On line 3, the last item (
'shorts') is accessed using its position in the array (
3) and logged to the console.
An array can contain items of differing data types. For example, you can create an array that stores both numbers and strings. You can even nest an array inside of another array to create a two-dimensional array.
var twoDimensional = [[41, 13], [7, 29]];
The array in this example is two-dimensional because it contains two nested arrays. Each nested array contains two numbers. In order to access items inside of the nested arrays, you must first access one of the nested arrays by index. Then, you can access an item inside of that array by its index.
console.log(twoDimensional); // access first array
console.log(twoDimensional); // access 13 in first array
In the example above, the first line logs the array
[41, 13] to the console. The second line logs
13 to the console. The code,
twoDimensional, accesses the first element in the array, which is the array
[41, 13]. The code on line 2,
twoDimensional, accesses the first element (
[41, 13]) and then accesses the second element in this nested array,
The output of this code is: