Arrays
Explore arrays, how to create and manipulate them, access elements, and use array methods.
Accessing Array Elements in JavaScript
Understanding Array Indices
In JavaScript, arrays are ordered collections of data. Each item in an array is called an element. To access these elements, we use their index. The index is the element's position in the array. It's important to remember that array indices start at 0, not 1. This means the first element has an index of 0, the second has an index of 1, and so on.
Accessing Elements Using Their Index
To retrieve a specific element, you use square brackets []
followed by the element's index number.
Example
let myArray = ["apple", "banana", "cherry"];
// Accessing the first element (index 0)
let firstElement = myArray[0]; // firstElement will be "apple"
// Accessing the second element (index 1)
let secondElement = myArray[1]; // secondElement will be "banana"
// Accessing the third element (index 2)
let thirdElement = myArray[2]; // thirdElement will be "cherry"
console.log(firstElement); // Output: apple
console.log(secondElement); // Output: banana
console.log(thirdElement); // Output: cherry
If you try to access an index that is out of bounds (i.e., greater than or equal to the array's length), JavaScript will return undefined
.
let myArray = ["apple", "banana", "cherry"];
// Trying to access an element beyond the array's length
let fourthElement = myArray[3]; // fourthElement will be undefined
console.log(fourthElement); // Output: undefined