Languages
[Edit]
EN

JavaScript - remove last item from array

0 points
Created by:
May87
827

In this article, we would like to show you how to remove the last item from array using JavaScript​​​​​​.

1. Using splice() method

In this example, to remove the last element from the array we use splice() method. 

// ONLINE-RUNNER:browser;

var array = ['a', 'b', 'c'];

array.splice(-1, 1); // splice(start, deleteCount)

console.log(array); // [a,b]

Note:

array.splice(-1, 1); is equal to array.splice(array.length - 1, 1);.

2. Using pop() method

In this example, we use pop() method that removes the last element from array and returns that element.

// ONLINE-RUNNER:browser;

var array = ['a', 'b', 'c'];

array.pop();

console.log(array); // [a,b]

3. Using slice() method

In this example, we use slice() method to create a shallow copy of an array from indexStart to indexEnd (not included).

// ONLINE-RUNNER:browser;

var array = ['a', 'b', 'c'];

var newArray = array.slice(0, -1); // slice(indexStart, indexEnd)

console.log(newArray); // [a,b]

Warning:

This approach doesn't really remove the last element, it copies the array omitting it.

References

  1. Array.prototype.splice() - JavaScript | MDN
  2. Array.prototype.slice() - JavaScript | MDN
  3. Array.prototype.pop() - JavaScript | MDN

Alternative titles

  1. JavaScript - remove last element from array
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join