JavaScript shift() Method Array.shift() method

This tutorial covers the shift() method, which belongs to the JavaScript Array object. The shift() method permanently deletes the first element of an array, and sends it back as return value.

The first array element itself is deleted, not just its value: the original array's second element becomes the first element of the modified array, and the array size (length) has decreased by one.

Related array method:
The unshift() method inserts an array element at the first position, pushing down other elements.

Using the shift() Method

The JavaScript code below declares a four-elements array, and deletes its first element by calling the shift() method.

var arlene = new Array("delta", "alpha", "beta", "gamma");

// Show shift()'s return value and modified array size
alert( arlene.shift() +"\n"+ arlene.length );

The JavaScript alert returned by the script above displays both the value returned by the shift() method, as well as the length of our array (after having called the shift() method.) JavaScript shift() method

Our modified array's length of 3 confirms that the operation was successful, and that shift() did in fact remove an element. The first array element ("delta") was in fact removed, and its value was returned.

Because the shift() method returns the array element it deleted, shift() has a return value of variable data type.

Make sure you scripts handle it appropriately, with type conversion methods if needed (the parseInt() and toString() methods, for example).

Test the shift() Method

Interactively test the shift() method by editing the JavaScript code below and clicking the Test shift() Method button.

Browser support for JavaScript shift() method
Internet Explorer supports the JavaScript shift() methodFirefox supports the JavaScript shift() methodSafari supports the JavaScript shift() methodOpera supports the JavaScript shift() method