How To Clear An Array in JavaScript

Array.prototype.length = 0; // This sets the array’s length property to 0

Checkout this video:


Arrays are a very important data structure in programming, and one of the most common operations on arrays is clearing them – that is, setting all of the elements in the array to some default value. In this article, we’ll discuss how to clear an array in JavaScript.

What is an Array?

An array is a linear data structure, or more simply put – it is a list. In JavaScript, an array can contain different types of data (including strings, numbers, objects, etc.). Arrays can be created using the array constructor method or the array literal syntax. There are numerous methods that can be used to manipulate arrays (e.g. push(), pop(), shift(), etc.).

In order to clear an array, there are two approaches that can be taken. The first is to simply set the length property of the array to 0:

array.length = 0;

The second approach is to use the built-in splice() method:

array.splice(0, array.length);

Why would you need to clear an Array?

There are a few reasons you might need to clear an Array in JavaScript:

-To release memory that is no longer needed (for example, if you’re finished using the Array and don’t plan to use it again)
-To empty an Array so it can be reused (for example, if you want to store a new set of data in the same Array)

The most common way to clear an Array is to set its length property to 0. This will remove all elements from the Array and will leave it empty:

myArray.length = 0;

Another way to clear an Array is to use the splice() method. The splice() method can be used to remove elements from an Array, but it can also be used to add new elements. To empty an Array using the splice() method, you can pass 0 as the second argument (the number of elements to remove):

myArray.splice(0, myArray.length);

How to clear an Array in JavaScript?

There are multiple ways to clear an Array in JavaScript. Some of the most common methods are using the Array.length property to set the Array’s length to 0 or using the delete keyword to delete elements from the Array. You can also use the splice method to remove elements from an Array.


So there you have it — four different ways to clear an array in JavaScript. Each method has its own pros and cons, so it’s important to choose the right one for your particular use case. In most cases, the built-in methods will probably be the best choice, but if you need more control over how the array is cleared, the For loop orArray.splice()method may be a better option.

Scroll to Top