This post will discuss how to erase elements from an array in JavaScript.

There are several ways to erase elements from an array in JavaScript, depending on which elements we want to remove and how we want to modify the original array. Here are some of the most common functions:

1. Using pop() function

To erase the last element of an array, we can use the pop() function, which removes and returns the last element of the array. The function modifies the original array by reducing its length by one. Here’s an example:

Download  Run Code

2. Using shift() function

To erase only the first element of an array, we can use the shift() function, which removes and returns the first element of the array. It also changes the length of the array and shifts the remaining elements to lower indexes. Here’s an example:

Download  Run Code

3. Using splice() function

To erase one or more elements from any position of an array, we can use the splice() function, which takes two or more arguments: the start index, the number of elements to delete, and optionally any elements to insert at that position. The function returns an array of the deleted elements and modifies the original array. Here’s an example:

Download  Run Code

4. Using filter() function

To erase elements from an array based on a condition, we can use the filter() function, which takes a callback function that returns true or false for each element. The function returns a new array with only the elements that pass the test and does not modify the original array. Here’s an example:

Download  Run Code

That’s all about erasing elements from an array in JavaScript.