Last Updated : 18 Sep, 2024
The shift() method in JavaScript is used to remove the first element of an array, reducing the array's length by one. This method is particularly useful for scenarios where elements need to be processed in the order they were added, such as in queue-like structures.
Syntax:arr.shift();Parameters:
Key PointsNote: This function can also be used with other javascript objects that behave like the array.
The function func()
removes the first element from array
using the shift()
method. The removed element is stored in the variable, value
, which is then logged to the console along with the modified array.
// Original array
let array = ["GFG", "Geeks", "for", "Geeks"];
// Checking for condition in array
let value = array.shift();
console.log(value);
console.log(array);
GFG [ 'Geeks', 'for', 'Geeks' ]Example 2: Removing First Element from Empty Array
The function func()
attempts to remove the first element from an empty array array
using the shift()
method. Since the array is empty, shift()
returns undefined
, which is logged to the console along with the unchanged array.
// Original array
let array = [];
// Checking for condition in array
let value = array.shift();
console.log(value);
console.log(array);
Example 3: Removing the First Element from the Nested Array
The function func() removes the first element from the nested array using the shift() method. The removed element is stored in the variable value, which is then logged to the console along with the modified array.
JavaScript
// Original array
let array = [1,[2,3,4],5,6];
// shift method on nested array
let value = array[1].shift();
console.log(value);
console.log("Array after operation: "+ array);
2 Array after operation: 1,3,4,5,6Supported Browsers:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4