Remove elements from an array in JavaScript

habtesoft
3 min readMar 15, 2023

In JavaScript, you can use several methods to remove elements from an array. Here are some of the most commonly used methods:

Not a Medium member? Read this article here

Method 1: Array.splice()

The splice() method is a built-in method in JavaScript that allows you to remove elements from an array by specifying the index of the element to start with and the number of elements to remove. Here's an example:

const fruits = ['apple', 'banana', 'orange', 'mango', 'kiwi'];
fruits.splice(2, 2);
console.log(fruits); // Output: ['apple', 'banana', 'kiwi']

In this example, we have an array of fruits and we use the splice() method to remove two elements starting from index 2 (i.e., 'orange' and 'mango').

Method 2: Array.pop()

The pop() method is a built-in method in JavaScript that removes the last element from an array and returns it. Here's an example:

const numbers = [1, 2, 3, 4, 5];
const lastNumber = numbers.pop();
console.log(numbers); // Output: [1, 2, 3, 4]
console.log(lastNumber); // Output: 5

In this example, we have an array of numbers and we use the pop() method to remove the last element (i.e., 5) and store it in a variable called…

--

--

habtesoft
habtesoft

Written by habtesoft

Passionate JavaScript developer with a focus on backend technologies. Always eager to connect and learn. Let’s talk, https://buymeacoffee.com/habtesoftat

No responses yet