How to Clear an Array in JavaScript

By Saheb Sutradhar - Updated On 12-03-2024

How to Clear an Array in JavaScript


How to Empty an Array in JavaScript, along with practical examples.

Emptying an array means removing all its elements, leaving it devoid of any content. Here are several ways to Clear an Array in JavaScript

 

1. Assigning a New Empty Array

This method creates a brand new empty array. Use it when you don’t have references to the original array elsewhere.

Example:

let myArray = [1, 2, 3, 4];
myArray = []; // Now myArray is an empty array

2. Setting the Length Property to 0

By setting the length property of an array to 0, you effectively clear its contents.
Works even in “strict mode” (ECMAScript 5).

Example:

let anotherArray = ['a', 'b', 'c', 'd', 'e', 'f'];
anotherArray.length = 0; // Clears the array


3. Using the splice() Method

The splice() method removes elements from an array.
It returns a copy of the original array with the removed items.

Example:

let yetAnotherArray = [10, 20, 30, 40];
yetAnotherArray.splice(0, yetAnotherArray.length); // Clears the array

4. Using pop() in a Loop

While not very succinct, this method clears the array by repeatedly calling pop() until its length becomes 0.

Example:

let arrayToClear = ['apple', 'banana', 'cherry'];
while (arrayToClear.length > 0) {
  arrayToClear.pop();
}

Remember that the choice of method depends on your specific use case. Whether you want to create a new array or modify the existing one, these techniques provide flexibility for handling arrays in JavaScript.

Happy coding! 

codelearningpoint © 2024