AppDividend
Latest Code Tutorials

Javascript Array Shift Example | Array.prototype.shift Tutorial

1

Javascript Array Shift Example | Array.prototype.shift Tutorial. The shift() method removes a first item from an array and returns that removed element. This method changes the length of the array on which we are calling the shift() method. Javascript Array Shift method is not pure function as it directly modifies the array.

If you want to learn more about the latest Javascript tutorials then check out this The Complete Javascript Course 2018.

Javascript Array Shift Example

The shift() method removes the item at the zeroeth index and shifts the values at consecutive indexes down, then returns that removed value. If we want to remove the last item of an array, use the pop() method.

If the length property is 0, undefined is returned.

The syntax for shift() method is following.

array.shift()

An array element can be a string, a number, an array, a boolean, or any other object types that are allowed in the Javascript array. 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 length of the array will be 2.

 

Javascript Array Shift Example | Array.prototype.shift Tutorial

Using shift() method in while loop

We can use the shift() method in while loop like this.

// 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. The shift() method removes the first element whereas the pop() method removes the last element of an array.

Finally, Javascript Array Shift Example | Array.prototype.shift Tutorial is over.

1 Comment
  1. Post says

    It works really well for me

Leave A Reply

Your email address will not be published.

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