Last Updated : 22 Nov, 2024
In JavaScript elements can be inserted at the beginning, end, and at any specific index. JS provides several methods to perform the operations.
At the BeginningThis operation inserts an element at the start of the array. The unshift() method is commonly used, which mutates the original array and returns its new length.
JavaScript
let a = [10, 20, 30, 40];
let e = 50;
a.unshift(e);
console.log(a);
[ 50, 10, 20, 30, 40 ]
You can insert an element at the beginning of an array using many other methods. Refer to this article for more methods.
At the EndTo add an element to the end of the array, the push() method is widely used. It mutates the array and returns its updated length.
JavaScript
let a = [10, 20, 30, 40];
let e = 50;
a.push(e);
console.log(a);
[ 10, 20, 30, 40, 50 ]
You can insert an element at the end of an array using many other methods. Refer to this article for more methods.
At a Given PositionTo insert an element at a specific index, the splice() method can be used. This method allows adding elements at any position in the array while optionally removing existing ones.
JavaScript
let a = [10, 20, 30, 40];
let pos = 2;
let e = 50;
a.splice(pos, 0, e);
console.log(a);
[ 10, 20, 50, 30, 40 ]
You can insert an element at a specific position in an array using many other methods. Refer to this article for more methods.
Multiple ElementsUsing the splice() method, you can also insert multiple elements at a specified index.
JavaScript
let a = [10, 20, 30, 40];
let pos = 2;
let e1 = 50, e2 = 60;
a.splice(pos, 0, e1, e2);
console.log(a);
[ 10, 20, 50, 60, 30, 40 ]
You can insert multiple elements into an array using many other methods. Refer to this article for more methods.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4