JavaScript Array methods Push, Pop, Unshift and Shift
In this tutorial, we will learn about how to add or remove items from the beginning or end of the arrays by using four different methods in JavaScript.
Push() method
The push() method is used to add the new elements to the end of an array.
Example:
const arr = ["paper", "painter", "poet"];
arr.push("pan");
console.log(arr); // ["paper", "painter", "poet", "pan"]
Pop() method
The pop()
method is used to remove the last element from an array, and returns the removed element.
const arr = ["paper", "painter", "poet"];
console.log(arr.pop()); // "poet"
console.log(arr); // ["paper", "painter"]
Unshift() method
The unshift()
method is used to add the new elements at the beginning of an array.
const arr = ["paper", "painter", "poet"];
arr.unshift("pocket");
console.log(arr); // ["pocket", "paper", "painter", "poet"]
Shift() method
The shift()
method is used to remove the first element from an array, and returns the removed element.
const arr = ["paper", "painter", "poet"];
console.log(arr.shift()); // "paper"
console.log(arr); // ["painter", "poet"]