How to Remove First and Last Elements from an Array in JavaScript

Updated onbyAlan Morel
How to Remove First and Last Elements from an Array in JavaScript

Arrays are a great way to store data because they can hold multiple values in a single variable.

However, sometimes you want to remove the first or last element of an array for whatever reason.

In this post, we'll learn how you can use built-in functions to remove the first and last elements from an array in JavaScript.

How to remove the first element

Let's start out with an example array of strings:

JAVASCRIPT
const places = ["Paris", "London", "New York", "Tokyo"];

Now, let's say we want the first element from this array. The best way to remove it from this array is to use the shift method.

This method will remove the first element from the array and return it.

JAVASCRIPT
const places = ["Paris", "London", "New York", "Tokyo"]; const first = places.shift(); console.log(first); console.log(places);
BASH
Paris ["London", "New York", "Tokyo"]

Alternatively, you can use the splice method to remove the first element by passing in 0 as the first argument and 1 as the second argument.

JAVASCRIPT
const places = ["Paris", "London", "New York", "Tokyo"]; const first = places.splice(0, 1); console.log(first); console.log(places);
BASH
["Paris"] ["London", "New York", "Tokyo"]

Keep in mind that the difference is that the shift method returns the removed element, while the splice method returns an array of the removed elements, in this case, just a single element.

How to remove the last element

If you're instead interested in removing an element, you can use the pop method, which works the same way as shift but removes the last element.

JAVASCRIPT
const places = ["Paris", "London", "New York", "Tokyo"]; const last = places.pop(); console.log(last); console.log(places);
BASH
Tokyo ["Paris", "London", "New York"]

Similar, you can also use the splice method to remove the last element by passing in the index of the last element as the first argument and 1 as the second argument.

JAVASCRIPT
const places = ["Paris", "London", "New York", "Tokyo"]; const last = places.splice(places.length - 1, 1); console.log(last); console.log(places);
BASH
["Tokyo"] ["Paris", "London", "New York"]

Like before, the difference is that the pop method returns the removed element, while the splice method returns an array of all the removed elements, even if it is just a single element, which is the case here.

Conclusion

In this post, we learned how to remove the first and last elements from an array in JavaScript.

Simply use the methods shift and pop to remove the first and last elements from an array.

Thanks for reading this post!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.