The JavaScript Array.prototype.unshift() method adds one or more elements to the beginning of an array and returns the new length of the array. This method modifies the original array and is useful when you need to prepend elements to an existing array.
Syntax
array.unshift(element1, element2, /* …, */ elementN);
Parameters
Parameters | Description |
---|---|
element1, element2, /* …, */ elementN | The elements to add to the front of the array. |
Return Value
Value | Description |
---|---|
Number | Returns the new length of the array after the elements have been added. |
Example 1: Basic Usage
This example demonstrates how to use the unshift() method to add elements to the beginning of an array.
let arr = [2, 3, 4]; let newLength = arr.unshift(1); console.log("Array: " + arr); console.log("New Length: " + newLength);
Output:
Array: 1, 2, 3, 4
New Length: 4
Example 2: Adding Multiple Elements
This example shows how to add multiple elements to the beginning of an array using unshift().
let arr = [3, 4, 5]; let newLength = arr.unshift(1, 2); console.log("Array: " + arr); console.log("New Length: " + newLength);
Output:
Array: 1, 2, 3, 4, 5
New Length: 5
Example 3: Adding Different Data Types
This example demonstrates how unshift() handles different data types.
let arr = [4, 5]; let newLength = arr.unshift(1, "two", 3); console.log("Array: " + arr); console.log("New Length: " + newLength);
Output:
Array: 1, two, 3, 4, 5
New Length: 5
Example 4: Using unshift() on an Empty Array
This example shows how unshift() behaves when used on an empty array.
let arr = []; let newLength = arr.unshift("a", "b", "c"); console.log("Array: " + arr); console.log("New Length: " + newLength);
Output:
Array: a, b, c
New Length: 3
Example 5: Repeated Use of unshift() Method
This example demonstrates repeated use of unshift() to continuously add elements to the beginning of an array.
let arr = [3]; arr.unshift(2); arr.unshift(1); console.log("Array: " + arr);
Output:
Array: 1, 2, 3
Supported Browsers
Chrome | Edge | Firefox | Opera | Safari |
---|---|---|---|---|
1 | 12 | 1 | 4 | 1 |