How to Check if a JavaScript Array is Empty

When using JavaScript, if you want to know if an array is empty or not, you can use .length property,

The length property of an array returns its size. If it is 0, the array is empty.

const languages = [];
if(languages.length == 0){
	console.log('this array is empty');
}

If the length property returns number bigger than 0, the array is not empty.

const languages = ['Java', 'JavaScript', 'Kotlin', 'Dart'];
if(languages.length > 0){
	for(var i = 0; i < languages.length; i++)	{
		console.log(languages[i]);
	}
}

We can loop through array normally after checking if it is empty or not.

Leave a Comment

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

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close