Array.unshift()
The Array.unshift()
method in JavaScript adds one or more elements to the beginning of an array and returns the new length of the array. It modifies the original array.
Syntax
</>
Copy
unshift()
unshift(element1)
unshift(element1, element2)
unshift(element1, element2, /* …, */ elementN)
Parameters
Parameter | Description |
---|---|
element1, element2, ..., elementN | The elements to add to the beginning of the array. |
Return Value
The unshift()
method returns the new length of the array after the specified elements are added to the beginning.
Examples
1. Adding a Single Element
This example demonstrates how to add a single element to the beginning of an array.
</>
Copy
const numbers = [2, 3, 4];
const newLength = numbers.unshift(1);
console.log(numbers);
console.log(newLength);
Output
[1, 2, 3, 4]
4
numbers.unshift(1)
adds1
to the beginning of thenumbers
array.- The return value is the new length of the array, which is
4
.
2. Adding Multiple Elements
You can add multiple elements to the beginning of an array in a single call.
</>
Copy
const fruits = ["banana", "cherry"];
const newLength = fruits.unshift("apple", "orange");
console.log(fruits);
console.log(newLength);
Output
["apple", "orange", "banana", "cherry"]
4
fruits.unshift("apple", "orange")
adds"apple"
and"orange"
to the beginning of thefruits
array.- The new length of the array is
4
.
3. Using unshift()
on an Empty Array
The unshift()
method can be used to add elements to an empty array.
</>
Copy
const emptyArray = [];
const newLength = emptyArray.unshift(5, 10);
console.log(emptyArray);
console.log(newLength);
Output
[5, 10]
2
The array emptyArray
now contains the elements [5, 10]
, and its length is 2
.
4. Modifying the Original Array
The unshift()
method directly modifies the original array.
</>
Copy
const letters = ["b", "c"];
letters.unshift("a");
console.log(letters);
Output
["a", "b", "c"]
The unshift()
method modifies the letters
array by adding "a"
at the beginning.