Borislav Hadzhiev
Thu Oct 07 2021·2 min read
Photo by Andrew Ly
To get the first and last elements of an array, access the array at index 0
and the last index. For example, arr[0]
returns the first element, whereas
arr[arr.length - 1]
returns the last element of the array.
const arr = ['a', 'b', 'c', 'd']; const first = arr[0]; console.log(first); // 👉️ a const last = arr[arr.length - 1]; console.log(last); // 👉️ d
0
and the last element in the array has an index of arr.length - 1
.To get the index of the last element we subtract 1
from the array's length,
because the first element in the array has an index of 0
.
If you had to get the second last element from an array you would have to
subtract 2
from the array's length.
Note that trying to access an array element at an index that does not exist does
not throw an error, instead it returns undefined
.
const arr = []; const first = arr[0]; console.log(first); // 👉️ undefined const last = arr[arr.length - 1]; console.log(last); // 👉️ undefined