javascript interactive

JavaScript Interactive — a console crash course


2.6 Indexed Access (Arrays)

Warning: Your browser may be outdated or unsupported.

The JavaScript console is known to display some of the examples incorrectly in Internet Explorer 8 or older.
>>>
var arr = ['a', 'b', 'c'];


  
>>>
arr[0]
"a"
The array index syntax is used to access array elements by their position in the array. The elements are zero-indexed.
>>>
arr[5] = 'd'
"d"
Similar to objects, the assignment operator is used to modify or set new values in the array.
>>>
arr
["a", "b", "c", undefined, undefined, "d"]
If the index used in the assignment is beyond the current array boundaries, it is extended with new undefined elements as needed.
>>>
arr.length
6
The special length property will be automatically updated to reflect the number of elements currently in the array.
>>>
arr.length = 3
3
The length property can also be assigned a value, which will truncate or lengthen the array as needed.
>>>
arr
["a", "b", "c"]
>>>
arr.push('d')
4
The simplest way to add an element to the end of an array is to use the built-in push() method.
>>>
arr[arr.length] = 'e';

  
Another way to add an element uses the length property.
>>>
arr
["a", "b", "c", "d", "e"]
>>>

Index 1 2 3 4 5 6 7 8