Array .push() / pop() / shift() / unshift()
Methods for adding and removing elements at the end or beginning of an array. push() and pop() operate on the end, while unshift() and shift() operate on the beginning.
Syntax
// Adds one or more elements to the end of the array. array.push(element1, element2, ...); // Removes and returns the last element of the array. var removed = array.pop(); // Adds one or more elements to the beginning of the array. array.unshift(element1, element2, ...); // Removes and returns the first element of the array. var removed = array.shift();
Method List
| Method | Description |
|---|---|
| push(element) | Adds one or more elements to the end of the array and returns the new length of the array. |
| pop() | Removes the last element from the array and returns that element. Returns undefined when called on an empty array. |
| unshift(element) | Adds one or more elements to the beginning of the array and returns the new length of the array. |
| shift() | Removes the first element from the array and returns that element. Returns undefined when called on an empty array. |
Sample Code
var fruits = ["apple", "orange"];
// Adds an element to the end.
fruits.push("grape");
console.log(fruits); // Outputs "apple,orange,grape".
// Removes the last element.
var last = fruits.pop();
console.log(last); // Outputs "grape".
console.log(fruits); // Outputs "apple,orange".
// Adds an element to the beginning.
fruits.unshift("banana");
console.log(fruits); // Outputs "banana,apple,orange".
// Removes the first element.
var first = fruits.shift();
console.log(first); // Outputs "banana".
console.log(fruits); // Outputs "apple,orange".
Overview
These four methods are the most fundamental ways to manipulate elements at the end and beginning of an array. push() and pop() operate on the end, while unshift() and shift() operate on the beginning. All four are mutating methods that modify the original array directly.
push() can add multiple elements at once by passing them as comma-separated arguments, and its return value is the new length of the array. pop(), on the other hand, takes no arguments and returns the removed element itself. These two methods are commonly used together to implement a stack (last-in, first-out) data structure.
To add or remove elements in the middle of an array, use splice().
Browser Compatibility
4.5 or earlier ×
3 or earlier ×
Android Browser
37+ ○
Chrome Android
36+ ○
17 or earlier ×
Firefox Android
79+ ○
3 or earlier ×If you find any errors or copyright issues, please contact us.