In JavaScript, the shift() method is used to remove the first element from an array and return that element. This method modifies the original array directly.
Syntax:
array.shift()
- array: The array from which the first element will be removed.
Example:
let fruits = ['apple', 'banana', 'orange'];
let shiftedFruit = fruits.shift();
console.log(shiftedFruit); // Output: "apple"
console.log(fruits); // Output: ['banana', 'orange']
Explanation:
- In the example, shift() removes the first element ('apple') from the fruits array and returns it.
- After calling shift(), the original array is modified, and the first element is removed. Subsequent elements are shifted to lower indices.
The shift() method provides a straightforward way to remove the first element from an array, making it useful for various data manipulation tasks in JavaScript.