Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

Array.prototype.unshift

Adds elements to the beginning of an array.

Available since: ES3

Syntax

array.unshift(element1, element2, /* … */)

Parameters

ParameterTypeDescription
element1, …anyElements to add to the beginning.

Return value

numberThe new length of the array.

Examples

Adding to the beginning:

const list = ['b', 'c'];
list.unshift('a');
 
console.log(list);

Output:

[
  "a",
  "b",
  "c"
]

The method returns the new length, not the array:

const list = ['c'];
 
console.log(list.unshift('a', 'b'));
console.log(list.join(''));

Output:

3
abc

Notes

The method changes the array itself. To get a new array and keep the old one, use spread: ['a', ...list].

See also

Related recipes

In the tutorial

  • Arrays — What an array is in JavaScript: creating one, indexes, length, changing elements and nested arrays.

Thanks for reading!

Donate to the site — we work hard for you.