The shift() method of the Array class in JavaScript removes the first element from an array and returns that element.
The syntax of Array.shift() method is:
shift()
This shift() method of Array removes the first element from an array and returns that element.
Array.shift() returns value of type Any
.
In JavaScript, we can use the shift() method to remove and return the first element from an array.
For example,
const arr = [1, 2, 3, 4, 5];
const removedElement = arr.shift();
console.log(removedElement);
1
If the array is empty, shift() method returns undefined.
For example,
const emptyArr = [];
const result = emptyArr.shift();
console.log(result);
undefined
In this JavaScript tutorial, we learned about shift() method of Array: the syntax and few working examples with output and detailed explanation for each example.