JavaScript Array unshift()

Posted by

JavaScript Array unshift()

The JavaScript Array.unshift() method adds one or more elements to the beginning of an array and returns the new length of the array. It is used to add an element to the beginning of an array.

Syntax

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

array.unshift(element1[, ...[, elementN]])

[/dm_code_snippet]

Parameters

element1, …, elementN: The elements to add to the front of the array.

Return Value

The new length of the array.

Description

The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array. It changes the length of the array.

Example

The following example creates an array, then uses unshift() to add two elements to the beginning of the array.

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

var array = [1, 2, 3];

console.log(array.unshift(4, 5));
// expected output: 5

console.log(array);
// expected output: Array [4, 5, 1, 2, 3]

[/dm_code_snippet]

In this example, the unshift() method adds 4 and 5 to the beginning of the array and returns the new length of the array.

Browser Support

The unshift() method is supported by all modern browsers.