Question

How to Empty an Array in JavaScript

Question

Is there a way to empty an array in JavaScript, possibly using a method such as .remove()?

For example:

let copyA = [1, 2, 3, 4];

How can I remove all items from copyA so that it becomes an empty array?

Short Answer

You will learn several ways to empty a JavaScript array and, most importantly, when to mutate the existing array versus replace it with a new one. This distinction matters whenever more than one variable refers to the same array.

Concept

Arrays are objects in JavaScript, which means variables hold a reference to an array rather than copying its contents automatically.

There are two main ways to make an array empty:

  1. Mutate the existing array: remove its elements while preserving the same array object.
  2. Reassign the variable: make one variable point to a brand-new empty array.

The shortest mutation approach is:

copyA.length = 0;

This changes the existing array by setting its length to zero. It is usually the best choice when other code might also hold a reference to that array.

You can also reassign the variable:

copyA = [];

This is simple, but it only updates copyA. Any other variable that refers to the original array will still see the old elements.

JavaScript arrays do not have a built-in .remove() method for clearing every item. Methods such as .splice() or .pop() can remove items, but they are usually less direct for this specific task.

Mental Model

Think of an array as a whiteboard and a variable as a label pointing to that whiteboard.

  • copyA.length = 0 erases everything on the same whiteboard. Everyone looking at that board sees it become empty.
  • copyA = [] gives the copyA label a new blank whiteboard. Other labels may still point to the old board, which still contains its original values.

This difference is called mutation versus reassignment.

Take Quiz

Syntax and Examples

Set .length to 0 to clear an existing array:

let copyA = [1, 2, 3, 4];

copyA.length = 0;

console.log(copyA); // []

length is a writable property of JavaScript arrays. Reducing it removes elements beyond the new length. Setting it to 0 removes all indexed elements.

You can also use splice():

let copyA = [1, 2, 3, 4];

copyA.splice(0, copyA.length);

console.log(copyA); // []

splice(start, deleteCount) removes items from an array. Starting at index 0 and deleting the current length removes everything.

Reassignment creates a new array instead:

let copyA = [1, 2, 3, 4];

copyA = [];

console.log(copyA); // []

Use reassignment when no other part of your program needs to retain a reference to the original array.

Step by Step Execution

Consider two variables that refer to one array:

const copyA = [1, 2, 3, 4];
const backup = copyA;

copyA.length = 0;

console.log(copyA);  // []
console.log(backup); // []

Step by step:

  1. copyA is created and refers to an array containing four numbers.
  2. backup = copyA does not copy the array. Both variables refer to the same array.
  3. copyA.length = 0 removes every element from that existing array.
  4. Since backup refers to the same array, it also sees an empty array.

Now compare reassignment:

let copyA = [1, 2, 3, 4];
const backup = copyA;

copyA = [];

console.log(copyA);  // []
console.log(backup); // [1, 2, 3, 4]

Here, copyA = [] changes only what copyA refers to. backup still refers to the original array.

Real World Use Cases

Clearing arrays is useful when an array represents temporary, reusable state:

  • Form validation: clear an errors array before validating the form again.
  • Search results: remove old results before filling an existing results collection with new data.
  • Game loops: clear a list of events, collisions, or particles after processing a frame.
  • Batch processing: empty a queue after sending its jobs to an API.
  • Data imports: reuse an array that stores rows from the current file before reading the next file.

For example, clearing validation errors in place can be useful if a UI component already observes the same array:

const errors = [];

function validateUser(user) {
  errors.length = 0;

  if (!user.email) {
    errors.push("Email is required.");
  }

  return errors;
}
Take Quiz

Real Codebase Usage

In real projects, the decision usually depends on ownership and references.

Reassign local temporary arrays

When the array is local and not shared, reassignment is clear:

function getActiveNames(users) {
  let names = users
    .filter((user) => user.active)
    .map((user) => user.name);

  // Later, if the local list is no longer needed:
  names = [];
}

Clear shared or exported arrays in place

When an array is shared through an object, module, or callback, mutation preserves its identity:

const state = {
  notifications: ["Saved", "Profile updated"]
};

function dismissAllNotifications() {
  state.notifications.length = 0;
}

Prefer replacing immutable state when a framework expects it

Some state-management patterns use immutable updates so changes are easy to detect:

const nextState = {
  ...state,
  notifications: []
};

The right choice is determined by the surrounding code's expectations. Do not mutate arrays that are meant to be treated as immutable.

Common Mistakes

Expecting array = [] to clear every reference

let items = [1, 2, 3];
const savedItems = items;

items = [];

console.log(savedItems); // [1, 2, 3]

items now refers to a new array. The original array was not changed. Use items.length = 0 if savedItems must also observe the clearing.

Using const with reassignment

This is invalid:

const items = [1, 2, 3];
items = []; // TypeError

A const variable cannot be reassigned. However, its array can still be mutated:

const items = [1, 2, 3];
items.length = 0;

Calling a non-existent .remove() method

const items = [1, 2, 3];
items.remove(); // TypeError: items.remove is not a function

Standard JavaScript arrays have no .remove() method. Use .length = 0, .splice(), or another supported array method.

Removing items with a loop unnecessarily

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

This works, but it is verbose and generally less clear than items.length = 0. Use repeated pop() only when you need to process each removed item.

Comparisons

ApproachChanges existing array?Keeps shared references in sync?Notes
array.length = 0YesYesUsually the clearest in-place clearing method.
array.splice(0, array.length)YesYesCan be useful if you also need the removed items.
array = []No; creates a new arrayNoGood for unshared variables or immutable update patterns.
while (array.length) array.pop()YesYesWorks, but use it only when each removed value matters.

splice() returns the removed elements:

const items = [1, 2, 3];
const removed = items.splice(0);

console.log(items);   // []
console.log(removed); // [1, 2, 3]

By contrast, assigning array.length = 0 does not return the removed values.

Take Quiz

Cheat Sheet

// Recommended when references must keep pointing to the cleared array
array.length = 0;

// Clear in place and receive removed elements
const removed = array.splice(0);

// Replace one variable's array with a new empty array
let array = [1, 2, 3];
array = [];
  • Arrays are reference values.
  • Use .length = 0 to empty the current array object.
  • Use =[] to point a variable at a new empty array.
  • A const array can be mutated, but the variable cannot be reassigned.
  • JavaScript does not provide a standard Array.prototype.remove() method.

FAQ

What is the best way to empty an array in JavaScript?

Use array.length = 0 when you want to clear the existing array and preserve shared references.

Does array = [] empty the original array?

No. It makes that variable refer to a new empty array. Other variables can still refer to the original array with its original values.

Can I clear an array declared with const?

Yes. You can mutate it with array.length = 0 or array.splice(0). You cannot use array = [] because that reassigns the variable.

Is there an Array .remove() method in JavaScript?

No. Standard arrays do not have .remove(). Use splice() to remove by position or length = 0 to remove all items.

Does splice(0) empty an array?

Yes. Calling array.splice(0) removes all elements from index 0 onward and returns them in a new array.

Which is faster: length = 0 or splice()?

For normal application code, choose based on clarity and whether you need the removed elements. length = 0 directly expresses that you want to clear the array.

Take Quiz

Mini Project

Description

Build a small task-list utility that can add tasks, display them, and clear all tasks. It demonstrates the difference between clearing a shared array in place and replacing a local array.

Goal

Create a task list whose clearTasks() function empties the same array that other code can reference.

Requirements

Create an array containing at least three task strings. Create a function that adds a task to the array. Create a function that displays the current tasks. Create a function that clears tasks in place. Keep a second variable referencing the task array and verify that it also sees the cleared list.

Take Quiz

Keep learning

Related questions

View more