Remove the last Element from an Array in JavaScript

JavaScript remove last element from array example; In this tutorial you will learn how to remove the last element from an array in JavaScript.

We can remove the last element from an array using three ways:

1. Using pop() Method

In javascript to remove the last element from an array, we can use the pop() method on the array. The pop method removes the last element from the array and returns it. The method mutates the original array, changing its length.

const arr = [1, 2, 3, 4];

const removeLast = arr.pop();
console.log(removeLast); // 4

console.log(arr); // [1, 2, 3]

If we call the Array.pop method on an empty array, it doesn’t throw an error, instead it returns undefined.

const arr = [];

const removeLast = arr.pop();
console.log(removeLast); // undefined

console.log(arr); // []

2. Using splice() function

The splice() method is often used to in-place remove existing elements from the array or add new elements to it.

const arr = [1, 2, 3, 4];

const withoutLast = arr.slice(0, -1);
console.log(withoutLast); // [1, 2, 3]

console.log(arr); // [1, 2, 3, 4]

You can easily extend the above code to remove the last n elements from the array:

const arr = [1, 2, 3, 4];
let n = 2;

arr.splice(arr.length - n);
console.log(arr);// [1, 2]

3. Using Lodash Library

If you’re using the Lodash JavaScript library in your project, you can use the initial() method, which returns everything but the last element of the array. Note that this doesn’t modify the original array but returns a new array.

var _ = require('lodash');

let arr = [1, 2, 3, 4];

arr = _.initial(arr);
console.log(arr); // [1, 2, 3]