Borislav Hadzhiev
Tue Oct 05 2021·3 min read
Photo by Kristina Wagner
Use the Array.at()
method to get the last element of an array in JavaScript,
e.g. const last = arr.at(-1)
. When passed a negative index, the at()
method
returns an element by counting back from the end of the array.
const arr = ['a', 'b', 'c']; const last = arr.at(-1); console.log(last); // 👉️ "c"
We used the Array.at method to get the last element of an array in JavaScript.
The only parameter the method takes is the index
of the array element to be
returned.
The at()
method returns the element in the array that matches the provided
index or undefined
if the given index cannot be found.
You can check that the last
variable does not store an undefined
value in
one of the following ways:
const arr = ['a', 'b', 'c']; const last = arr.at(-1); console.log(last); // 👉️ "c" if (last !== undefined) { console.log(last.toUpperCase()); // 👉️ "C" } console.log(last?.toUpperCase()); // "C"
The if
statement and the
optional chaining (?.)
operator exclude the possibility of the value being undefined
, which enables
us to use type-specific built-in methods.
The optional chaining (?.) operator short-circuits, instead of throwing an
error, if the reference is undefined
or null
.
Alternatively, you can access the element at the last array index.
To get the last element of an array in JavaScript, access the array at index
array.length - 1
, e.g. const last = arr[arr.length - 1]
. The calculation
evaluates to the index of the last element in the array.
const arr = ['a', 'b', 'c']; const lastElement = arr[arr.length - 1]; console.log(lastElement); // 👉️ c
1
from the array's length to get the index of the last element in the array.Other ways to get the last element of an array, include Array.pop
and
Array.slice
.
You can get the last element of an array, by calling the pop
method on the
array. The pop
method mutates the original array, removes and returns its last
element.
const arr = ['a', 'b', 'c']; // 👇️ mutates the original array const lastElement = arr.pop(); console.log(lastElement); // 👉️ c console.log(arr) // 👉️ ['a', 'b']
The Array.pop method returns the last element of the array, but it also mutates the original array.
Calling the pop
method on the array removes the last element, leaving the
array with just 2 elements. This can be confusing if you have to perform other
operations on the array.
To get the last element of an array:
-1
as an argument to the Array.slice
methodconst arr = ['a', 'b', 'c']; const lastElement = arr.slice(-1)[0]; console.log(lastElement); // 👉️ c
Passing -1
to the
Array.slice
method means that we want a new array containing only the last element of the
original array.
We then assign the only element in the new array to a variable.
Array.slice
method does not mutate the original array, instead it returns a new array.