Skip to content

JavaScript empty array | Check and Clear Examples

  • by

You can check JavaScript empty array doing by check for undefined first and then the length of it, if the length is zero then the array is empty.

If you want to clear/empty an array in JavaScript, then there are multiple ways to it like Substituting with a new array, Setting the length prop to 0, Splice the whole array, etc.

The simple, easy and safe way to do it is:

arr.length = 0;

Example of check JavaScript empty array

First, check undefined in if statement. If the first condition true then check array length.

If you do it the other way round, it will generate an error if the array is undefined.

If you want to check undefined condition also then use (===) equality operator for it.

Let’s see the example of Check if array has empty values JavaScript.

<!DOCTYPE html> 
<html>
  
<body> 
    <script type="text/javascript"> 

    var array1= [];

    if (array1 !== undefined || array1.length == 0) {
    	alert("Empty array")
	}

    </script> 
      
    
</body> 
  
</html> 

Output:

JavaScript empty array

Examples of doing empty an array in JavaScript

There are multiple ways to do it, let’s see one by one:-

Substituting with a new array

<!DOCTYPE html> 
<html>
  
<body> 
    <script type="text/javascript"> 

    var array1= [1, 2, 3, 4]

    array1 = [];
    	
    alert(array1)


    </script> 
    
</body> 
  
</html> 

Output: Empty array

empty an array in JavaScript

Setting length prop to 0

This will clear the existing array by setting its length to 0.

<script type="text/javascript"> 

    var array1= [1, 2, 3, 4]

    array1.length = 0;

</script> 

Splice the whole array

This will remove all elements from the array.

<script type="text/javascript"> 

    var array1= [1, 2, 3, 4]
    array1.splice(0, array1.length)

    alert(array1)

</script> 

Read more about it: Remove element from Array JavaScript

Using Loops

 It is the slowest solution.

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

Q: How to Declare an empty array in JS?

Answer: Simple see below code:-

var array1 = [];

Do comment if you have any doubts and suggestion on this question. Let’s us know which one is best way to do it.

Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version

Leave a Reply

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