What is the opposite of JavaScript push() method that works reverse?

By Faruque Ahamed Mollick

We have already discussed the JavaScript push method in this post – Add or append a new item to an array in JavaScript using push() method. We have learned that the push() method add or append the new item to the end of an array().

Now in this post, we are going to discuss the opposite of push method in JavaScript. That means, now we will remove the item from an array using a method of javaScript.

Locate the Geo-position of a visitor in JavaScript

How to generate a random password in JavaScript?

To go forward, let’s assume that we have an array contains some city name:

var cities = ["London", "Dubai", "New York", "Jakarta", "Manila"];

JavaScript has a method which is pop() method that removes the last item from an array. Below is an example of using array pop() method:

var cities = ["London", "Dubai", "New York", "Jakarta", "Manila"];

cities.pop(); // Remove the last item from the array
console.log(cities);

In the above code, we have an array contains with some cities and using pop() method we have removed the last item from the cities array. The new array will be:

["London", "Dubai", "New York", "Jakarta"];

 



However, if we want to remove the first item of an array then how to do it?

Well, JavaScrpt has shift() method that works just like the pop() method, but instead of removing the last item of an array, it removes the first item. Now to remove the first item from the array we need.

Below is the code to remove the first item from an array:

var cities = ["London", "Dubai", "New York", "Jakarta", "Manila"];

cities.shift();   // Remove the first item from the array
console.log(cities);

Now it will return the array that is given below:

 ["Dubai", "New York", "Jakarta", "Manila"];

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *