The Array.shift()
method is a built-in JavaScript function used to remove the first element from an array and return it. This method modifies the original array, reducing its length by one.
Syntax
arr.shift();
Parameters
The shift()
method does not take any parameters.
Return Value
The shift()
method returns:
- The removed first element of the array if the array is not empty.
undefined
if the array is empty.
Example 1: Removing the First Element
let arr = [10, 20, 30, 40, 50]; let item = arr.shift(); console.log(item); // Output: 10 console.log(arr); // Output: [20, 30, 40, 50]
Example 2: Using shift()
on an Empty Array
let arr = []; let item = arr.shift(); console.log(item); // Output: undefined console.log(arr); // Output: []
When the array is empty, shift()
method returns undefined
without causing an error.
Example 3: Processing Elements in a Queue
let tasks = ['task1', 'task2', 'task3']; while (tasks.length > 0) { let currentTask = tasks.shift(); console.log(`Processing: ${currentTask}`); } // Output: // Processing: task1 // Processing: task2 // Processing: task3
Supported Browsers
Browser | Support |
---|---|
Chrome | 1+ |
Firefox | 1+ |
Safari | 1+ |
Edge | 12+ |
Opera | 4+ |
Internet Explorer | 5.5+ |