Remove first and last element from an array in JavaScript


In this article we will learn how to remove the first and last element from an array in JavaScript.

JavaScript have some in-built function which helps us to add or remove elements from an array easily.

Using this methods, we can remove the first or the last element or even an specific element at an given index from an array.

Since this article is about removing the first and last element, we will be using the pop() and shift() method of JavaScript.

array.pop() - Remove Last Element

The pop() method in JavaScript removes the last element from an array and return the removed element.

pop() changes the length of the array.

Lets see the example:

Here we will remove the last element i.e leopard from the animals array.

const animals = ['tiger', 'rhino', 'giraffe', 'camel', 'leopard'];

console.log(animals.pop());
// output: "leopard"

console.log(animals);
// output: Array ['tiger', 'rhino', 'giraffe', 'camel'];

array.shift() - Remove First Element

The shift() method in JavaScript removes the first element from an array and return the element.

shift() changes the length of the array and also the remaining elements index shift down.

Example

const animals = ['tiger', 'rhino', 'giraffe', 'camel', 'leopard'];

console.log(animals.shift());
// output: "tiger"

console.log(animals);
// output: Array [rhino', 'giraffe', 'camel','leopard'];

If you want to remove an element from a specific index from an array, you can learn about it here, Remove A Specific Item From An Array In JavaScript

Related Topics:

How To Empty An Array in JavaScript?

Append Item To Array In JavaScript

How To Copy Or Clone An Array In JavaScript

Merge Two Arrays And Remove Duplicates


💾 Recommended Articles