How to Remove All Items From an Array in JavaScript

Remove All Items From an Array in JavaScript

There are several approaches to remove all items from an array in JavaScript, and your choice depends on whether you want to mutate the original array or create a fresh one. In this tutorial, we’ll explore some of those approaches, with examples and explanations.

Method 1: Set length = 0 (Fastest Mutable Approach)

The simplest way to empty an array is by setting its length property to 0. This method modifies the original array in place and is especially useful when you want to retain the same reference.

const fruits = ["apple", "banana", "cherry"];

fruits.length = 0;

console.log(fruits);
[]

Method 2: Using splice() to Remove All Elements

splice() is typically used to remove specific items, but you can also use it to remove every element. This is a clean, readable method that also mutates the original array.

const fruits = ["apple", "banana", "cherry"];

fruits.splice(0, fruits.length);

console.log(fruits);
[]

Method 3: Reassign to a New Empty Array (Immutable)

If you don't care about preserving references and simply want a new empty array, you can just reassign the variable to a new array. This is ideal in functional or immutable contexts.

let fruits = ["apple", "banana", "cherry"];

fruits = [];

console.log(fruits);
[]

Method 4: Using while Loop with pop()

For educational purposes or if you need to perform some cleanup on each element, using a while loop with pop() is a clear option. This removes elements from the end one by one.

const fruits = ["apple", "banana", "cherry"];

while (fruits.length > 0) {
  fruits.pop();
}

console.log(fruits);
[]

Comparison Table

Method Mutates Original? Preserves Reference? Best For
length = 0 Yes Yes Performance and memory efficiency
splice() Yes Yes Clean readable syntax
= [] No No Immutability and functional programming
while (pop()) Yes Yes Element-wise cleanup logic

Comments

💬 Please keep your comment relevant and respectful. Avoid spamming, offensive language, or posting promotional/backlink content.
All comments are subject to moderation before being published.


Loading comments...