How to add an element to the beginning of an array in JavaScript

Home / JavaScript / How to add an element to the beginning of an array in JavaScript


How to add an element to the beginning of an array in JavaScript

You can add one or more elements to the beginning of a JavaScript array with the unshift() method. The method will return the new length of the array.
 

Syntax

Parameters

element1 … elementN

The elements to add to the front of the array.

Return value

The new length property of the object upon which the method was called.

Examples

This is a basic example that shows how to add a single element at the beginning of an array.

You can also add multiple elements at once to an array:

Adding another array with unshift, however, adds the array as a whole and does not add the separate elements to the array:

If you want to add all elements af an array to the beginning of another array, you can use the concat() method.

Conclusion

In this article we have seen that you can add one or more distinct elements to the beginning of a JavaScript array but you cannot merge another array into it.

See also

Array.prototype.concat()

Array.prototype.push()