An array elements (values) can be accessed using index (key). To access an element in an array, you specify an index in the square brackets []
.
The index of an array starts from zero in JavaScript. In other words, the first element of an array starts at index 0, the second element starts at index 1, and so on.
You access an array element by referring to the index number: [0] is the first element. [1] is the second element.
const myArray = ['h', 'e', 'l', 'l', 'o'];
// first element
console.log(myArray[0]); // "h"
// second element
console.log(myArray[1]); // "e"
var stringArray = new Array("one", "two", "three", "four");
stringArray[0]; // returns "one"
stringArray[1]; // returns "two"
stringArray[2]; // returns "three"
stringArray[3]; // returns "four"
var numericArray = [1, 2, 3, 4];
numericArray[0]; // returns 1
numericArray[1]; // returns 2
numericArray[2]; // returns 3
numericArray[3]; // returns 4
An array index must be numeric.
Changing an Array Element
const cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Opel"; //This statement changes the value of the first element in cars array
Accessing the Last Array Element
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits[fruits.length - 1];
Looping Array Elements
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fLen = fruits.length;
let text = "<ul>";
for (let i = 0; i < fLen; i++) {
text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";