Array Indexing
In JavaScript, arrays use numbered indexes. From left to right, index number starts from 0.
Access an element
Similar to string, array elements are accessed using square brackets to enclose the index number: arr[i]
.
Change array element
Contrary to string, an array is mutable, which means you can change its contents. We can assign new value to an element using array index:
arr[i] = new value
We can replace an element, or add a new item to the array.
Example:
let fruits = ["Apple", "Orange", "Banana"];
// access array elements
alert( fruits[0] ); // Apple
alert( fruits[1] ); // Orange
alert( fruits[2] ); // Banana
// change an item
fruits[1] = 'Bear';
// add an new item
fruits[3] = 'Monkey';
// changed array
console.log(fruits); // ["Apple", "Bear", "Banana", "Monkey"]
// last element:
console.log(fruits[3]); // Monkey
console.log(fruits[fruits.length - 1]); // Monkey (also the last item)
console.log(fruits.length); // 4
In previous example, fruits[3]
, and fruits[fruits.length - 1]
all point to the same item: the last element in the array.
The length
Property
Similar to string, the length property has the array length, it simply returns the total number of elements in the array:
let dates = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
alert(dates.length); // 7