Last updated: Mar 1, 2024
Reading timeยท2 min
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 has an index of arr.length - 1
.You can get the element by accessing the array at index 0
.
const arr = ['a', 'b', 'c', 'd']; const first = arr[0]; console.log(first); // ๐๏ธ a
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
.
const arr = ['a', 'b', 'c', 'd']; const last = arr[arr.length - 1]; console.log(last); // ๐๏ธ d
If you had to get the second last element of an array, you would subtract 2
from the array's length.
const arr = ['a', 'b', 'c', 'd']; const last = arr[arr.length - 2]; console.log(last); // ๐๏ธ c
Trying to access an array element at an index that doesn't exist doesn't throw
an error, it returns undefined
.
const arr = []; const first = arr[0]; console.log(first); // ๐๏ธ undefined const last = arr[arr.length - 1]; console.log(last); // ๐๏ธ undefined
You can also use the Array.at()
method.
For example, arr.at(0)
returns the first element and arr.at(-1)
returns the
last array element.
const arr = ['a', 'b', 'c', 'd']; const first = arr.at(0); console.log(first); // ๐๏ธ a const last = arr.at(-1); console.log(last); // ๐๏ธ d
We used the Array.at() method to get the first and last elements in an array.
Array.at()
method takes an integer that represents the index of the value to be returned.To get the first element, simply pass 0
to the Array.at()
method.
const arr = ['a', 'b', 'c', 'd']; const first = arr.at(0); console.log(first); // ๐๏ธ a
The method supports negative integers to count backward. For example, -1
returns the last element in the array and -2
returns the second last element.
const arr = ['a', 'b', 'c', 'd']; const last = arr.at(-1); console.log(last); // ๐๏ธ d const secondLast = arr.at(-2); console.log(secondLast); // ๐๏ธ c
We passed a value of -1
to the Array.at()
method to get the last element of
the array.
The Array.at()
method returns the element at the specified index or
undefined
if the index is out of range.
You can learn more about the related topics by checking out the following tutorials: