JavaScript Insert Element in an array (original) (raw)
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 Beginning
This 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);
`
Output
[ 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 End
To 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);
`
Output
[ 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 Position
To 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);
`
Output
[ 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 Elements
Using 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);
`
Output
[ 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.