JavaScript push and pop methods
In JavaScript, the push
and pop
methods are commonly used to add and remove elements from the end of an array. These methods modify the original array and are very efficient for managing data in a stack-like fashion (Last-In-First-Out or LIFO).
1. Array push()
Method
- Purpose: The
push()
method adds one or more elements to the end of an array and returns the new length of the array. - Syntax:
array.push(element1, element2, ..., elementN)
- Returns: The new length of the array after the elements have been added.
Example:
let fruits = ["Apple", "Banana"];
let newLength = fruits.push("Orange");
console.log(fruits); // Output: ["Apple", "Banana", "Orange"]
console.log(newLength); // Output: 3
Explanation: In this example, the string
"Orange"
is added to the end of thefruits
array. Thepush()
method then returns the new length of the array, which is 3.Multiple Elements: You can also push multiple elements at once.
Example:
let newFruits = fruits.push("Grape", "Pineapple");
console.log(fruits); // Output: ["Apple", "Banana", "Orange", "Grape", "Pineapple"]
console.log(newFruits); // Output: 5
2. Array pop()
Method
- Purpose: The
pop()
method removes the last element from an array and returns that element. This operation modifies the array and decreases its length by 1. - Syntax:
array.pop()
- Returns: The element that was removed from the array.
Example:
let lastFruit = fruits.pop();
console.log(fruits); // Output: ["Apple", "Banana", "Orange", "Grape"]
console.log(lastFruit); // Output: "Pineapple"
Explanation: In this example, the
pop()
method removes the last element ("Pineapple"
) from thefruits
array and returns it. Thefruits
array is now shorter by one element.Empty Array: If the
pop()
method is called on an empty array, it returnsundefined
.
Example:
let emptyArray = [];
let poppedElement = emptyArray.pop();
console.log(poppedElement); // Output: undefined
console.log(emptyArray); // Output: []