JavaScript Reference Library →

How to Remove All Items From an Array in JavaScript

How to Remove All Items From an Array in JavaScript

This reference explains an individual array operation. For the learning sequence, start with JavaScript arrays and array transformations.

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

Apply the operation carefully

Check whether the operation changes the original array, and test empty inputs and missing matches. Compare related operations in the reference library.

Reference checks are optional and do not count toward course progress.

    Reference library →