Skip to content

JavaScript clear array | Example code

  • by

There are multiple ways to clear an array in JavaScript. A simple way is to assign it to a new empty array. Four ways to clear an array in JavaScript.

JavaScript clear array

A simple example code removes all elements of the Array.

Assigning: the fastest way to empty an array

<!DOCTYPE html>
<html>
<body>

  <script>
    let a = [1,2,3];
    console.log(a)
    
    a = [];
    console.log(a)
  </script>

</body>
</html> 

Output:

JavaScript clear array

Setting length to zero

By setting the length property to 0, all the elements in the array are removed, effectively clearing the array.

array.length = 0;

pop() method

Remove each element of the array one by one using the while loop and pop() method:

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

Alternatively, you can also use the splice() method to remove all elements from the array:

let myArray = [1, 2, 3, 4, 5];
myArray.splice(0, myArray.length);

console.log(myArray); // Output: []

The splice() method can be used to remove elements from an array by specifying the starting index (0 in this case) and the number of elements to remove (the current length of the array in this case).

Comment if you have any doubts or suggestions on this JS Array topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *