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
and the last index. For example,
arr 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; console.log(first); // 👉️ a const last = arr[arr.length - 1]; console.log(last); // 👉️ d
0and 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
If you had to get the second last element from an array you would have to
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
const arr = ; const first = arr; console.log(first); // 👉️ undefined const last = arr[arr.length - 1]; console.log(last); // 👉️ undefined