JavaScript Array.shift() Method

Usage — The JavaScript Array.shift() method is used to remove the first element from an array and return that element. This method changes the length of the array.

It has the following syntax:

JavaScript

arr.shift()

Here is an example of using Array.shift():

JavaScript

var primes = [18, 2, 3, 5, 7, 11, 13];
var removed = primes.shift();

// Output — [2, 3, 5, 7, 11, 13]
console.log(primes);

// Output — 18
console.log(removed);

Return Value — This method returns the removed element from the array. It returns undefined if the array is empty.

Additional Information — The Array.shift() method removes the element at the zeroth index and shifts the values at consecutive indexes down, then returns the removed value. If the length property is 0, undefined is returned.

This method is intentionally generic which means that you can be call it on all objects resembling arrays. Objects which do not contain a length property reflecting the last in a series of consecutive, zero-based numerical properties may not behave in any meaningful manner.

Browser Support — The Array.shift() method is available in Chrome, Edge, Firefox, Internet Explorer 5.5+, Opera and Safari.

Go Directly To — usage, parameters or working examples.

Parameters

This method does not accept any parameters.

Working Examples

Here are some examples of using the Array.shift() method:

JavaScript

var names = ["Andrew", "Edward", "Paula", "Christina", "John"];

while( (i = names.shift()) !== undefined ) {
    console.log('Just removed ' + i);
}

/* Output —
Just removed Andrew
Just removed Edward
Just removed Paula
Just removed Christina
Just removed John
*/

Further Reading

  1. You can read more about the JavaScript Array.shift() method on MDN.
  2. You can also take a look at the defeinition of JavaScript Array.shift() method in the ECMAScript 2015 specification.

Reader Comments

1. You can register or login to post a comment. Asking readers to register improves the quality of discussion.

2. As a registered user, you will also get to access features like choosing between a light and dark theme or anything else that we might implement in future.

Follow Us For Updates

FacebookTwitterGoogle+
Go To Top