To access elements in a JavaScript array, use the index number inside square brackets []
. Arrays are zero-indexed, meaning the first element is at index 0
.
Key Points
- Zero-Indexed: The first element is at index
0
. - Access Syntax: Use square brackets
[]
with the index. - Out of Bounds: Accessing an index that doesn’t exist returns
undefined
.
Examples
Basic Access
let fruits = ['Apple', 'Banana', 'Orange'];
console.log(fruits[0]); // Output: 'Apple'
console.log(fruits[1]); // Output: 'Banana'
Accessing the Last Element
To access the last element, use array.length - 1
:
let lastFruit = fruits[fruits.length - 1];
console.log(lastFruit); // Output: 'Orange'
Looping Through Array Elements
Use loops to access each element.
Using a for
Loop
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
Using forEach
fruits.forEach(function(fruit) {
console.log(fruit);
});
Practical Tips
Modifying Elements: Change an element by assigning a new value:
fruits[1] = 'Mango';
console.log(fruits); // Output: ['Apple', 'Mango', 'Orange']