How do you remove an element from an array in JavaScript?

In Javascript, there are several ways to remove an element from an array:

Two of them are - using splice() method and using pop() method.

Using splice() method:

You can remove an element from an array using the splice() method.

For example:

let array = [1, 2, 3, 4, 5];
array.splice(2, 1); // remove the element at index 2
console.log(array); // [1, 2, 4, 5]

In the example above, splice() is called on the array and passed two arguments: the index of the element to remove (in this case, 2), and the number of elements to remove (in this case, 1). This removes the element at index 2 from the array.

Notes:

The splice() modifies the original array in place, so you don’t need to assign the result to a new variable.

Using pop() method:

Using pop() method, you can remove last element from the array.

For example:

let array = [1, 2, 3, 4, 5];
array.pop(); // removes the last element
console.log(array); // [1,2,3,4];

That’s all.

Thank you for reading, and let’s have conversation with each other

Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.

Read more: