JavaScript Array shift()
Syntax & Examples
Array.shift() method
The shift() method of the Array class in JavaScript removes the first element from an array and returns that element.
Syntax of Array.shift()
The syntax of Array.shift() method is:
shift()
This shift() method of Array removes the first element from an array and returns that element.
Return Type
Array.shift() returns value of type Any
.
✐ Examples
1 Using shift() method to remove and return the first element
In JavaScript, we can use the shift() method to remove and return the first element from an array.
For example,
- We define an array variable arr with elements [1, 2, 3, 4, 5].
- We use the shift() method on arr to remove and return the first element.
- The first element, which is 1, is removed from arr and stored in the variable removedElement.
- We log removedElement to the console using console.log() method.
JavaScript Program
const arr = [1, 2, 3, 4, 5];
const removedElement = arr.shift();
console.log(removedElement);
Output
1
2 Using shift() method on an empty array
If the array is empty, shift() method returns undefined.
For example,
- We define an empty array variable emptyArr.
- We use the shift() method on emptyArr.
- The shift() method returns undefined as the array is empty.
- We log the return value to the console using console.log() method.
JavaScript Program
const emptyArr = [];
const result = emptyArr.shift();
console.log(result);
Output
undefined
Summary
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.