How to Use the shift() Method in JavaScript Arrays?
Learn how to use the JavaScript shift() method to remove and return the first element of an array effectively.
341 views
To use shift in JavaScript, simply call the `shift()` method on an array. This method removes the first element from the array and returns it. If the array is empty, it returns `undefined`. For example: ```javascript let fruits = ['apple', 'banana', 'cherry']; let firstFruit = fruits.shift(); console.log(firstFruit); // Outputs: 'apple' console.log(fruits); // Outputs: ['banana', 'cherry'] ```
FAQs & Answers
- What does the shift() method do in JavaScript? The shift() method removes the first element from an array and returns that element. If the array is empty, it returns undefined.
- Does shift() modify the original array in JavaScript? Yes, shift() modifies the original array by removing its first element.
- What is the difference between shift() and pop() in JavaScript arrays? shift() removes the first element of an array, while pop() removes the last element.