Remove first and last element from an array in JavaScript

featured Image

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'];

Related Topics:

Merge Two Arrays And Remove Duplicates

Related Posts

featured Image

Get the 10 characters from a string using JavaScript.

Here, in this article we will learn how to get the first 10 character from any string using JavaScript. Here we will be using JavaScript’s String method substring. What is…

Read more
featured Image

Convert date to long date format using JavaScript

In this article we will look into how to convert a date to a long date format using JavaScript. To convert it to a long format we will be using…

Read more
featured Image

Prevent body from scrolling when a modal is opened

Here, in this article, we will learn how to prevent the body from scrolling when a modal or a pop-up is opened using JavaScript. The scroll event is not cancelable….

Read more