Developed By
Gautam Kumar - Full stack developer
DEEP DIVE INTO
In JavaScript, the shift() method removes the first element from an array and returns that element. It modifies the original array by removing the first item, and if the array is empty, it will return undefined.
javascriptconst removedElement = array.shift();
array: The array from which you want to remove the first element.
removedElement: The element that was removed from the array.
javascriptconst fruits = ['apple', 'banana', 'cherry'];
const firstFruit = fruits.shift();
console.log(fruits); // Outputs: ['banana', 'cherry']
console.log(firstFruit); // Outputs: 'apple' (the removed element)
In this example, the shift()
method removes the first element ('apple') from the fruits array and assigns it to the firstFruit variable.
The shift()
method is commonly used when you want to remove and retrieve elements from the beginning of an array, effectively shifting all remaining elements to lower indices.