Last Updated : 23 Jul, 2025
To insert an element at a specific position in a JavaScript array, the JS splice() method is used.
JavaScript
let a = [10, 20, 30, 40];
let e = 50;
let i = 2;
a.splice(i - 1, 0, e);
console.log(a);
[ 10, 50, 20, 30, 40 ]Using built-in Method
The JavaScript splice() method is used to insert elements at a specific position in JS Array.
JavaScript
let a = [10, 20, 30, 40];
a.splice(4, 0, 50);
console.log(a);
[ 10, 20, 30, 40, 50 ]Writing Your Own Method
To add an element at a given index in an array, shift all the elements from that index to the right and then insert the new element at the required index.
JavaScript
let a = [10, 20, 30, 40];
let e = 50;
let p = 2;
// Shifting elements to the right
for (let i = a.length; i >= p; i--)
a[i] = a[i - 1];
// Insert the new element at index pos - 1
a[p - 1] = e;
console.log(a);
[ 10, 50, 20, 30, 40 ]
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