JavaScript unshift() Method Array.unshift() method

This tutorial covers the unshift() method, from the JavaScript Array object. The unshift() method inserts one or more array elements, passed as arguments, at the start of an array. (Do not confuse with the shift() method, which removes and returns the first element of an array.)

Related array method:
The push() method inserts an array element at the first position, pushing down other elements, while splice() inserts elements anywhere in an array.

Using the unshift() Method

The script below creates an array, and calls the unshift() method to add new elements before its first element.

var arlene = new Array("first", "second", "third", "fourth");

// Unshift two elements and return new array size
arlene.unshift("newFirst", "newSecond");

alert( arlene.length.toString() );

The JavaScript alert displays the updated size (length) of our array. With most JavaScript interpreters, the unshift() method returns the length of the modified array — see "Caution", further down. JavaScript unshift() method

In Firefox, Safari, and Opera, the unshift() method returns the length of the modified array (after new elements have been added). This is not the case in Internet Explorer (which returns "undefined").

Test the unshift() Method

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

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