Array Operations in JavaScript (Push, Pop, Shift and Unshift)

Suneet Agrawal
2 min readMay 16, 2023

JavaScript is a powerful programming language that offers several ways to manipulate arrays, which are one of the most commonly used data structures in JavaScript. Four important array manipulation methods are push, pop, shift, and unshift. These methods allow you to add and remove elements from the beginning or end of an array. In this blog, we will discuss these methods and their usage in JavaScript.

This post was originally posted at https://agrawalsuneet.github.io/blogs/array-operations-in-javascript-push-pop-shift-unshift/ and later reposted on Medium.

Push Method in JS

The push() method is used to add one or more elements to the end of an array. It takes one or more arguments, which are the elements that you want to add to the array. The push() method modifies the original array and returns the new length of the array.

For example:

let myArray = [1, 2, 3];
myArray.push(4);
console.log(myArray); // [1, 2, 3, 4]

In the above example, we have an array of three elements. We then use the push() method to add a fourth element to the end of the array. The resulting array now has four elements.

Pop Method in JS

The pop() method is used to remove the last element from an array. It takes no arguments and modifies the original array. The pop() method returns the removed element.

For example:

let myArray = [1, 2, 3];
let removedElement = myArray.pop();
console.log(removedElement); // 3
console.log(myArray); // [1, 2]

In the above example, we first declare an array of three elements. We then use the pop() method to remove the last element from the array. The removed element is stored in the removedElement variable, and the resulting array has two elements.

Shift Method in JS

The shift() method is used to remove the first element from an array. It takes no arguments and modifies the original array. The shift() method returns the removed element.

Please continue reading at https://agrawalsuneet.github.io/blogs/array-operations-in-javascript-push-pop-shift-unshift/

That’s all for now. You can read my other interesting blogs here or you can enjoy my games or apps listed here. Feel free to use my open-source Android components in your app listed here. Or drop an email, if you didn’t find what you are looking for and need some help.

--

--