JavaScript Array Add and Remove Methods
Arrays allow you to store multiple values in a single variable. JavaScript provides several methods to add and remove elements from an array.
In this article, you will learn the four most commonly used array methods:
- push()
- pop()
- shift()
- unshift()
Array push()
The push() method adds one or more elements to the end of an array.
Syntax
arrayName.push(element1, element2, …);
Parameters
- element1 → First element to add.
- element2… → Additional elements (optional).
Return Value: Returns the new length of the array.
Example
let fruits = ["Apple", "Banana"];
fruits.push("Mango");
console.log(fruits);Output
[“Apple”, “Banana”, “Mango”]
Array pop()
The pop() method removes the last element from an array.
Syntax
arrayName.pop();
Return Value: Returns the removed element.
Example
let fruits = ["Apple", "Banana", "Mango"];
fruits.pop();
console.log(fruits);Output
[“Apple”, “Banana”]
Array shift()
The shift() method removes the first element from an array.
Syntax
arrayName.shift();
Return Value: Returns the removed element.
Example
let fruits = ["Apple", "Banana", "Mango"];
fruits.shift();
console.log(fruits);Output
[“Banana”, “Mango”]
Array unshift()
The unshift() method adds one or more elements to the beginning of an array.
Syntax
arrayName.unshift(element1, element2, …);
Parameters
- element1 → First element to add.
- element2… → Additional elements (optional).
Return Value: Returns the new length of the array.
Example
let fruits = ["Banana", "Mango"];
fruits.unshift("Apple");
console.log(fruits);Output
[“Apple”, “Banana”, “Mango”]
Method Comparison
| Method | Action | Position | Returns |
| push() | Adds element | End | New array length |
| pop() | Removes element | End | Removed element |
| unshift() | Adds element | Beginning | New array length |
| shift() | Removes element | Beginning | Removed element |