Add new elements at the beginning of an array using JavaScript
Last Updated :
22 Dec, 2023
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:
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.
Javascript
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
In this method, we will use an array.splice method. The array.splice() method is used to modify the content of the array.
Example: The below example explians the use of the splice() method to add element at start of the array.
Javascript
let Arr = [1, 2, 3, 4, 5];
console.log(`Array Elements Before
element addition:
${Arr}`);
function myGFG() {
Arr.splice(0, 0, "6" );
console.log(`Array Elements After
element addition:
${Arr}`);
}
myGFG();
|
Output
Array Elements Before
element addition:
1,2,3,4,5
Array Elements After
element addition:
6,1,2,3,4,5
The Spread operator allows an iterable to expand in places where 0+ arguments are expected. It is mostly used in the variable array where there is more than 1 value is expected.
Example: The below example uses the spread operator to add element at the start of an array.
Javascript
let arr = [66, 85, 19, 7];
console.log(`Array Elements Before
element addition:
${arr}`);
arr = [34, ...arr];
console.log(`Array Elements After
element addition:
${arr}`);
|
Output
Array Elements Before
element addition:
66,85,19,7
Array Elements After
element addition:
34,66,85,19,7
The JavaScript Array concat() Method is used to merge two or more arrays together. This method helps to add new elements at the beginning of the array.
Example: The below example implements the concat() method to add element at the start of an array.
Javascript
const arr = [23, 45, 12, 67];
console.log(`Array Elements Before
element addition:
${arr}`);
console.log(`Array Elements After
element addition:
${[32].concat(arr)}`);
|
Output
Array Elements Before
element addition:
23,45,12,67
Array Elements After
element addition:
32,23,45,12,67
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...