We use arrays to store lists of items. Accessing array elements means getting a specific item from the list by its position.
0
0
Accessing array elements in Javascript
Introduction
When you want to get the first item in a list of names.
When you need to read a specific score from a list of game scores.
When you want to check the last item in a shopping list.
When you want to update a specific element in a list of tasks.
When you want to loop through a list and access each item by its position.
Syntax
Javascript
const arrayName = [item1, item2, item3]; const element = arrayName[index];
Array positions start at 0, so the first element is at index 0.
If you try to access an index outside the array, you get undefined.
Examples
Access the first element using index 0.
Javascript
const fruits = ['apple', 'banana', 'cherry']; const firstFruit = fruits[0]; // 'apple'
Access the last element using
length - 1.Javascript
const numbers = [10, 20, 30]; const lastNumber = numbers[numbers.length - 1]; // 30
Accessing any element in an empty array returns
undefined.Javascript
const emptyArray = []; const element = emptyArray[0]; // undefined
Accessing the only element in a single-item array.
Javascript
const colors = ['red']; const onlyColor = colors[0]; // 'red'
Sample Program
This program creates an array of animals and accesses elements at different positions, including an index that does not exist.
Javascript
const animals = ['dog', 'cat', 'rabbit']; console.log('Animals array:', animals); const firstAnimal = animals[0]; console.log('First animal:', firstAnimal); const secondAnimal = animals[1]; console.log('Second animal:', secondAnimal); const lastAnimal = animals[animals.length - 1]; console.log('Last animal:', lastAnimal); const outOfBounds = animals[5]; console.log('Out of bounds access:', outOfBounds);
OutputSuccess
Important Notes
Accessing an element by index is very fast, with time complexity O(1).
Trying to access an index outside the array returns undefined, which can cause bugs if not checked.
Use array length to find the last element's index, since arrays can change size.
Summary
Arrays store items in order, starting at index 0.
You get an element by using its index inside square brackets.
Accessing an invalid index returns undefined.