JavaScriptArrays

Array.prototype.unshift()

Adds elements to the start of an array and returns its new length.

Returns
The new length of the array.
Changes the original
Yes
On this page

Example

#
JavaScript
const notifications = ['New task']
notifications.unshift('Badge earned', '7-day streak')

console.log(notifications)
Console
['Badge earned', '7-day streak', 'New task']

Definition and usage

#

The unshift() method inserts one or more elements at the start of the array, pushing the existing elements further along. It returns the array’s new length.

Elements passed in one call keep their order: unshift("a", "b") gives an array that starts with "a", then "b".

The method changes the original. A non-mutating version is [newItem, ...items], often used in app state, for example when adding the newest notification to the top of a list.

Syntax

#
Syntax
array.unshift(element1, element2, …)

Parameters

#
  • element1…elementN

    any values

    The elements to insert at the start.

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • A non-mutating version: [newItem, ...items].
  • On very large arrays, frequent unshift() calls are slow, because every element has to shift over.

Related entries

#

Spotted a mistake or missing an example? Write to us.