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:
- Mutate the existing array: remove its elements while preserving the same array object.
- 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 = 0erases everything on the same whiteboard. Everyone looking at that board sees it become empty.copyA = []gives thecopyAlabel 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.
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:
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:
copyAis created and refers to an array containing four numbers.backup = copyAdoes not copy the array. Both variables refer to the same array.copyA.length = 0removes every element from that existing array.- Since
backuprefers 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.(backup);
Real World Use Cases
Clearing arrays is useful when an array represents temporary, reusable state:
- Form validation: clear an
errorsarray 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;
}
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,
: []
};
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 method
Comparisons
| Approach | Changes existing array? | Keeps shared references in sync? | Notes |
|---|---|---|---|
array.length = 0 | Yes | Yes | Usually the clearest in-place clearing method. |
array.splice(0, array.length) | Yes | Yes | Can be useful if you also need the removed items. |
array = [] | No; creates a new array | No | Good for unshared variables or immutable update patterns. |
while (array.length) array.pop() | Yes | Yes | Works, but use it only when each removed value matters. |
splice() returns the removed elements:
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 = 0to empty the current array object. - Use
=[]to point a variable at a new empty array. - A
constarray 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 ?
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.
Keep learning
Related questions
Abort Ajax Requests with jQuery jqXHR.abort()
Learn how to cancel an in-progress jQuery Ajax request with jqXHR.abort(), handle abort status safely, and avoid stale UI updates.
Access the Correct this Inside a JavaScript Callback
Learn why JavaScript this changes in callbacks and how to preserve an object context using bind, arrow functions, and event handler patterns.
Add Key-Value Pairs to JavaScript Objects
Learn how to add key-value pairs to JavaScript objects with dot and bracket notation, dynamic keys, examples, and common mistakes.