shift() in JavaScript – How to Remove First Array Element
Whenever you use shift() on an array, the method does the following:
- It removes its calling array's first item.
- It returns the removed item.
note
- A calling array is an array on which you used
shift()
. So, inbestColorsList.shift()
,bestColorsList
is the calling array. shift()
is sometimes written asArray.prototype.shift()
because it is a method of theArray
object'sprototype
property.
Syntax of the shift()
Method
shift()
accepts no argument. Here is the syntax:
callingArray.shift();
Example 1: Remove an Array's First Item
const numbersArray = [1, 2, 3, 4];
console.log(numbersArray.shift());
// The invocation above will return: 1
// Check the numbersArray's current content:
console.log(numbersArray);
// The invocation above will return:
[2, 3, 4];
You can see that shift()
removed and returned numbersArray
's first item (1
).
Also, note that shift()
changed the original array's length.
Example 2: Remove an Array's First Item
const fruitsArray = ["Mango", "Apple", "Orange"];
const removedFruit = fruitsArray.shift();
console.log(removedFruit); // returns "Mango"
console.log(fruitsArray); // returns ["Apple", "Orange"]
The snippet above used shift()
to shift away fruitsArray
's first item.
note
Overview
This article discussed what JavaScript's shift()
method does. We also used examples to see how it works.