JavaScript Array shift() method
The JavaScript Array shift() method allows you to remove the first element (at index zero) of your array, while also returning that element to you. The shift() method does not have any parameters.
Here’s an example of shift() in action:
let programmingLangs = ["JavaScript", "Ruby", "Python"];
let shiftedLang = programmingLangs.shift();
console.log(programmingLangs); // ["Ruby", "Python"]
console.log(shiftedLang); // "JavaScript"
Because the first element is a string, the value returned by shift() is also a string. If your array contains another array or an object, that will be returned as well:
let fruitCart = [
{
name: "Apple",
quantity: 3,
},
{
name: "Orange",
quantity: 1,
},
{
name: "Banana",
quantity: 3,
},
];
let shiftedFruit = fruitCart.shift();
console.log(shiftedFruit); // { name: "Apple", quantity: 3 }
You can use the shift() method for any array type data you have.
More JavaScript tutorials
See allJavaScript
Sort Keys in Map Using JavaScript
Dec 11, 2023
JavaScript
Get Element by Data Attribute Using JavaScript
Dec 8, 2023
JavaScript
Convert Milliseconds to Hours Minutes Seconds in JavaScript
Dec 6, 2023
JavaScript
JavaScript Get the Index of Max Value in Array
Nov 16, 2023
JavaScript
JavaScript Check if Value is an Object
Nov 15, 2023