Introduction
Getting the last element of a list/array is a common operation. In this tutorial, we'll take a look at how to get the last element in a JavaScript array/list.
JavaScript is a weakly-typed or untyped language, which means that the type of variable doesn't need to be declared before using it, since JavaScript determines the type by reading the variable's value.
var x = "something"
is evaluated, and x
is assigned to a String type. The same process applies to lists - you don't need to define a list's type, you can just fill the list up with values.
A list is defined by putting the elements in between the square brackets ([]
), where the elements can be heterogeneous (don't have to be of the same type):
var myList = ["Peter", "Smith", 25, 23, "Random String", 10]
JavaScript has a lot of built-in methods that can be used to manipulate lists like this one. Here are the ones we'll be using to get the last element.
Get Last Element Using length
The length
attribute of a list denotes the number of elements in a list:
console.log(myList.length)
Element indexing in arrays/lists in JavaScript is much akin to other languages. We can access an element, based on its index, by passing it in square brackets []
, referencing the array. The last element has the index of length-1
.
Since the length
field just returns the saved value of elements - this is a fast, efficient and cheap operation. The best way to get the last element of a JavaScript array/list is:
var lastElement = myList[myList.length - 1];
console.log(lastElement);
This results in:
10
Get Last Element Using pop()
The pop()
method returns the last element of a collection, but removes it during the process. Though, if we use the spread operator from ES6 - we can avoid this functionality by temporarily copying the list in memory, and performing pop()
on the copy, keeping the original list intact.
The pop() Method
Let's pop()
the last element off the list:
var lastElement = myList.pop();
console.log(lastElement)
console.log(myList)
This results in the list being cut short of that element:
10
["Peter", "Smith", 25, 23, "Random String"]
If you don't need the original list to stay intact, then you can pop elements off of it, but if you do need the original, you can make a copy and pop()
from it.
pop() with ES6' Spread Operator
ES6 is short for EcmaScript6, which is a JavaScript standard used to make programming in JavaScript easier (to code less, but do more).
It was founded back in 1997 and its first major breakthrough was in 2015, with the ES6 standard (or EcmaScript2015). The latest version is the 11th one, developed in 2020. All versions are meant to make coding easier in JavaScript (with new syntax rules, new keywords, etc.).
The feature that we can leverage here is the spread operator (...
).
Amongst other features, the spread operator can copy lists/arrays:
[...myList]
This generates a new list, with the same elements as myList
. That being said - we can pop()
from the new list instead of the original one:
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
console.log([...myList].pop())
console.log(myList)
This results in:
10
["Peter", "Smith", 25, 23, "Random String", 10]
Note: This may be convenient to write, but is not the cheapest of solutions, since it copies a list. For small lists, it doesn't reduce the performance by much, but with longer lists, this is an inefficient way to simply get the last element.
Get Last Element Using slice()
The slice(a, b)
method 'slices' the array from point a
to point b-1
- given that a
and b
are integers. In a more mathematical way, you can look at slice like this: [a, b)
- the element at a
is included, whilst the element at b
is not:
console.log(myList.slice(1, 4))
This results in a slice of the original array:
["Smith", 25, 23]
The slice()
method also accepts negative indexing - where it iterates through the collection backwards. So if we slice(-4, -1)
, the iteration will start from the third element from the back and end at one before the last one (because slice
doesn't include the b
point).
This allows us to simply include one last element, from the end of the list via slice()
:
console.log(myList.slice(-1))
Which results in:
[10]
This is still an array, so to get this element we access it with myList.slice(-1)[0]
- which will return our element:
console.log(myList.slice(-1)[0])
Note: slice()
is best used when you want to retrieve the last N elements of an array, rather than one, since you can simply use length-1
instead.
Get Last Element Using reverse()
The reverse()
method reverses the list in-place. The last element will become the first, and vice-versa:
console.log(myList.reverse())
The output will be:
[10, 'Random String', 23, 25, 'Smith', 'Peter']
Now our element is the first one, so we can access it with myListReversed[0]
.
Note: Reversing an array/list is also a potentially very expensive operation. Avoid reversing the collection if the only thing you want to do is access the last element. If you are to reverse it anyway - you can access the element like this. If not, refer to the first approach of using length-1
.
Conclusion
The cheapest, most efficient, and probably most intuitive method of these is the first - myList[myList.length()-1]
. This is what you'll be using most of the time.
Using pop()
removes the element from the list and returns it. If you want to remove the element - this is the approach you'll want to be using, since otherwise, you'll have to remove the element manually.
slice()
gives us a slice, which is a great approach if we want to get the last N elements.
reverse()
reverses the array in-place and should be avoided if you just want to get an element. If you're reversing the array anyway, though, this doesn't cost anything extra.