DEV Community

Cover image for The difference between Push, Pop, Shift and Unshift in Javascript Array

The difference between Push, Pop, Shift and Unshift in Javascript Array

Array is a very important concept in JavaScript and in programming as well. It is used to store related data in a single block. You can create it with the let, var or the const keyword.

//example
let arry = ["John", "Tobi", "Musa"];

Enter fullscreen mode Exit fullscreen mode

It has some amazing methods, but we'll only explore 4.

The push() method is used to add an element at the end of the array. It also returns the added element.

arry.push("Ifeanyi").
console.log(arry);
// the result will be
["John", "Tobi", "Musa", "Ifeanyi"];

The pop() method. It removes the last element in an array, it also returns the element.
arry.pop();
console.log(arry);
//the result will be
["john", "Tobi", "Musa"];

The shift() method. This method removes the first element in an array. It behaves like the pop() method but in an opposite direction.
arry.shift();
//the result will be
["Tobi", "Musa"];

The unshift() method. This method adds a new element at the beginning of an array. It also behaves like the push() method but in an opposite direction.
arry.unshift("Ayo");
//the result will be
["Ayo", "Tobi", "Musa];

Top comments (0)