Skip to content

JavaScript Array length 0 | Zero Check and set Array examples

  • by

Using Array length property can set or check array length 0 in JavaScript. This property returns the number of elements in the array. If the number is greater than 0, it evaluates to true.

Check Array length 0 or Not

Simple checking Array length.

<!DOCTYPE HTML> 
<html> 
<body> 

	<script>
		var arr1 = [1, 2, 3, 5, 2, 8, 9, 2];
		var arr2 = []
		
		console.log(arr1.length);
		console.log(arr2.length);
		
	</script> 
</body> 
</html>	

Output:

Simple checking Array length JavaScript

Checking zero with if-else condition

<script>
		var arr2 = []
		
		if (arr2.length)
			output = true;
		else
			output = false;

		console.log(output);

</script> 

Output: false

Set JavaScript Array length 0

The way to empty an array is to set its length to zero.

<!DOCTYPE HTML> 
<html> 
<body> 

	<script>
		var arr1 = [1, 2, 3, 5, 2, 8, 9, 2];

		arr1.length = 0;
		console.log(arr1);
	</script> 
</body> 
</html>	

Output:

JavaScript Array length 0

Do comment if you have any doubts and 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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading