JavaScript

JavaScript Array Push and Pop Method

Arrays are crucial when working in any programming language to complete programming tasks. Arrays store the same data types in javascript, such as strings, integers, arrays, and even functions.

When working with arrays, we frequently need to add or remove elements. The push() and pop() methods come to the rescue in this situation. In this post, we’ll go over what the push() and pop() functions in JavaScript are, as well as some examples to help you understand them better.

What are push() and pop() methods in JavaScript

push() is used to add an element/item to the end of an array.

The pop() function is used to delete the last element/item of the array.

Let’s try to add and remove elements from an array using push() and pop() methods to understand these methods better.

Note: We will use the browser console to demonstrate examples performed in this post. To open up the browser console:

  • Use the F12 key in Chrome and other chromium-based browsers.
  • Use CTRL + SHIFT + K keyboard shortcut keys for Mozilla.
  • Use Option + ⌘ + C keyboard shortcut keys in Safari (if developer menu does not appear, then open Preferences by pressing ⌘ +, and in Advanced tab check “Show Develop menu in menu bar”).

How to use the pop() method in JavaScript

Suppose we have an array of numbers and we want to remove the last element from it. The code from removing an element from the end of the array would go like this:

var intArr = [23, 45, 67];
intArr.pop(); // returns the removed item
console.log(intArr);

How to use the push() method in JavaScript

Similarly, if we want to add an element at the end of an array, the code for pushing or adding an element would go like this:

var intArr = [23, 45];
intArr.push(67); // returns the new array length
console.log(intArr);

Conclusion

The pop() method in JavaScript removes an item from the end of an array, whereas the push() method adds an item to the end of an array. The returning value of the pop() method is the item that is removed from the array. The returning value of the push() method is the number of elements in the array after the new element has been added. These two methods are used a lot when working with arrays in JavaScript. In this post, we have had a thorough discussion on what pop() and push() methods are in JavaScript and how to use them.

About the author

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.