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

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();
}

Do 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

Tags:

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.