Javascript shift: How to Remove First Item in the Array

3
48
Javascript array shift method tutorial with example

Javascript shift() method removes the item at the zeroeth index and shifts the values at consecutive indexes down, then returns that removed value.

Javascript shift

The array shift() is a built-in JavaScript function that removes the first element from the array and returns that deleted item. The array.shift() method does not accept any argument.

The shift() method changes the array’s length which we are calling the shift() method. The shift() method is not a pure function as it directly modifies the array.

To remove the last element of an array in Javascript, use the Javascript pop() method. If the length property is 0, undefined is returned.

Syntax

The syntax for the shift() method is the following.

array.shift()

An array element can be a string, a number, an array, a boolean, or any other object types allowed in the Javascript array.

Example

Let us take a simple example.

// app.js

let apps = ["Instagram", "Facebook", "Messanger"];
apps.shift();

console.log(apps);

The first item of the array will be removed, and the array’s length will be 2.

Javascript Array Shift Example | Array.prototype.shift Tutorial

Using shift() method in while loop

If we want to check a specific condition using the shift() function, we can use a while loop. For example, we can use the shift() method in a while loop like the below code.

// app.js

let names = ["Harvey", "Donna", "Mike", "Rachel" ,"Louis", "Jessica"];

while( (i = names.shift()) !== undefined ) {
    console.log(i);
}

So until the value of undefined is found, it will remove each item of an array.

Javascript Array Shift Example

The shift() method deletes and returns the removed element of the original array. All remaining elements in the array get shifted one slot to the left to fill the hole created by removing the first element. It will not create a new array.

Javascript shift() method removes the first element, whereas the pop() method removes the last element of an array.

That’s it for this tutorial.

See also

Javascript array push()

Javascript array pop()

Javascript array unshift()

3 Comments

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.