How to Insert and Delete Array Elements in JavaScript

Insertion and deletion are some of the most important operations in JavaScript array. We can achieve this by using different string methods.

Now we will see some such JavaScript methods.

Insert at the beginning

To add an element o the beginning of an array we will use unshift() method.

let anArray = [1, 5, 8];

//Output:[ 30, 1, 5, 8 ]

Delete from the beginning

To delete an element from the end of an array we can use shift() method.

let anArray= [1, 5, 8];

//output:[ 5, 8 ]

Inserting at the end

By using push() method we can add an element to array at the end.

let anArray= [1, 5, 8];

//Output: [1, 5, 8, 10]

Deleting from the end

By using the pop() method we can delete an element from the end of an array.

let anArray= [1, 5, 8, 10];
const popped = anArray.pop();

//Output: [1, 5, 8]

Deleting by delete keyword

There is a special keyword called delete. Using this operator we can delete an element but space will not be removed.

let anArray= [1, 5, 8];
delete anArray[2];
console.log(“After deletion:”, anArray);

//Output: After deletion: [ 1, 5, <1 empty item> ]

Software Engineer || Full Stack Developer || Technical Writer || Speaker