JavaScript shift and unshift methods
In JavaScript, the shift
and unshift
methods are used to manipulate arrays by adding or removing elements from the beginning of the array. These methods, like push
and pop
, modify the original array and are useful for managing data in a queue-like fashion (First-In-First-Out or FIFO).
1. Array unshift()
Method
- Purpose: The
unshift()
method adds one or more elements to the beginning of an array and returns the new length of the array. - Syntax:
array.unshift(element1, element2, ..., elementN)
- Returns: The new length of the array after the elements have been added.
Example:
let fruits = ["Banana", "Orange"];
let newLength = fruits.unshift("Apple");
console.log(fruits); // Output: ["Apple", "Banana", "Orange"]
console.log(newLength); // Output: 3
Explanation: In this example, the string
"Apple"
is added to the beginning of thefruits
array. Theunshift()
method returns the new length of the array, which is now 3.Multiple Elements: You can also unshift multiple elements at once.
Example:
let moreFruits = fruits.unshift("Grape", "Pineapple");
console.log(fruits); // Output: ["Grape", "Pineapple", "Apple", "Banana", "Orange"]
console.log(moreFruits); // Output: 5
2. Array shift()
Method
- Purpose: The
shift()
method removes the first element from an array and returns that element. This operation modifies the array and decreases its length by 1. - Syntax:
array.shift()
- Returns: The element that was removed from the array.
Example:
let firstFruit = fruits.shift();
console.log(fruits); // Output: ["Pineapple", "Apple", "Banana", "Orange"]
console.log(firstFruit); // Output: "Grape"
Explanation: In this example, the
shift()
method removes the first element ("Grape"
) from thefruits
array and returns it. Thefruits
array now starts with"Pineapple"
.Empty Array: If the
shift()
method is called on an empty array, it returnsundefined
.
Example:
let emptyArray = [];
let shiftedElement = emptyArray.shift();
console.log(shiftedElement); // Output: undefined
console.log(emptyArray); // Output: []
Summary:
unshift()
: Adds one or more elements to the beginning of an array and returns the new array length.shift()
: Removes the first element from an array and returns the removed element.