What is array unshift() in Javascript?

The Array.prototype.unshift() method inserts one or more elements into the beginning of an array, and returns the new length of the array.

arr.unshift(element1, element2, ..., elementN)

The unshift() method inserts one or more elements into the beginning of an array, and returns the new length of the array.

If you specify more than one element, the elements are inserted in the order that they are specified.

The elements are actually inserted into the array before the first element, and the array's length is increased by the number of elements inserted.

The following example inserts three elements into the beginning of the array a :

var a = [];
a.unshift(1);
a.unshift(2);
a.unshift(3);

The value of a is now [1, 2, 3] , and its length is 4.

The unshift() method can be used to insert an element into the beginning of an array without changing its length.

For example, the following code inserts an element into the beginning of the array a without increasing its length:

var a = [];
a.unshift(1);

The value of a is now [1] , and its length is 1.

💡
Need a writer? Want to work with me? I have a subscription copywriting service available at Zipply.io. Subscribe to a set number of words and split it into as many copy assets as you need. Scale your startup, small business, or MVP. Upgrade, downgrade and pause at any time. Start your subscription here.