How to use the Array unshift() method In Javascript
Adding new elements at the beginning of the existing array can be done by using the Array unshift() method. This method is similar to the push() method but it adds an element at the beginning of the array.
Syntax:
ArrayObject.unshift( arrayElement );
Parameters:
- ArrayObject: It is the array, where to insert the element.
- arrayElement: It is the element, which is to be inserted.
Return Value:
It will return the length of the array after adding the element.
Example: This example inserts element 6 at the beginning of the array.
let Arr = [1, 2, 3, 4, 5];
console.log(`Array Elements Before
adding the element at
start: ${Arr}`);
function myGFG() {
Arr.unshift("6");
console.log(`Array Elements After
adding the element at
start: ${Arr}`);
}
myGFG();
Output
Array Elements Before adding the element at start: 1,2,3,4,5 Array Elements After adding the element at start: 6,1,2,3,4,5
Add new elements at the beginning of an array using JavaScript
In this article, we will learn how to add new elements at the beginning of an array using JavaScript. We can do this by using the following methods:
Table of Content
- Using the Array unshift() method
- Using array.splice method
- Using the Spread operator
- Using Array concat() Method
- Using array destructuring
Contact Us