Array access
- Node.js course
- Beginner
- Lesson 54/116
- 4 min
Learn to access array elements by index.
Array access
To reach an element of an array you use an index: arr[0], arr[1] and so on. The index goes inside square brackets. Indexing is zero-based: the first element is arr[0], the second arr[1].
For example const fruits = ["apple", "pear", "banana"]; fruits[0] gives "apple", fruits[2] gives "banana". An index past the array length returns undefined; no error is thrown. For example fruits[5] is undefined. So checking array bounds with arr.length is a good habit.
Zero-based indexing
In JavaScript indices start at zero. This means the last element's index is arr.length - 1. In a three-element array the last element is arr[2], because the length is 3 and 3 - 1 = 2.
Zero-based indexing takes getting used to but is standard in programming. Negative indices are not directly supported; arr[-1] returns undefined. To reach the last element write arr[arr.length - 1]. As a shorter way arr.at(-1) can be used; this method supports negative indices.
Practice Print the second element
The fruits variable is set to ["apple", "pear", "banana"]. Declare a variable second and assign the result of fruits[1] to it. Then print second with console.log. The output on a single line must be pear.
Starter code
const fruits = ["apple", "pear", "banana"];
// Declare second with the second element and print itSample solution
const fruits = ["apple", "pear", "banana"];
const second = fruits[1];
console.log(second);Expected output
pear
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Access the first element
const fruits = ["apple", "pear", "banana"];
const first = fruits____;
const fruits = ["apple", "pear", "banana"];
const first = fruits[0];
Explanation: fruits[0] gives the first element.
2 What is const a = [10, 20, 30]; a[2]?
const a = [10, 20, 30];
a[2]- 20
- 30 Correct answer
- 10
- 3
Explanation: a[2] gives the third element, 30.
3 Match each index to its position
| Term | Meaning |
|---|---|
[0] |
First element |
[1] |
Second element |
[length - 1] |
Last element |
[length] |
undefined |