How to clear an array in JavaScript

Mo Ibra

Mo Ibra

Jan 2, 2023

In this article we will learn how to clear an array in JavaScript.

It is very common to clear an array in JavaScript in JavaScript.


Problem

Now we have a problem, which is that we want to clear an array.

Imagine you have a array like this:

[1, 2, 3, 4, 5];

And we want to clear an array to became output like this:

[]

How to solve this problem

The solution to this problem is easy, and there are more than one solution to this problem, such as:

  • Using length property
  • Using splice method
  • Using overwrite

Clear an array using length property

We can use length property to clear our array.

Let's see an example

// Array
const array = [1, 2, 3, 4, 5];

// Clear an array
array.length = 0;

// Result:
console.log(array);

Output

[]

The length data property of an Array instance represents the number of elements in that array. MDN


Clear an array using splice method

We can clear an array using splice method as well.

Let's see an example

// Array
const array = [1, 2, 3, 4, 5];

// Clear an array using `splice`
array.splice(0, array.length);

// Result:
console.log(array);

Output

[]

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. MDN


Clear an array using overwrite

You can overwrite the array with an empty array [] but you must

Example

// Array
let array = [1, 2, 3, 4, 5];

// Overwrite
array = [];

// Result:
console.log(array);

Thank you for reading

Thank you for reading my blog. 🚀

Suggestions For More Articles: