The best way to check check if an Array is empty is to use the array length method in JavaScript. If the length is equal to zero then the array is not empty else it array is empty.
JavaScript checks if Array is empty
Simple example code.
<!DOCTYPE html>
<html>
<body>
<script>
var myArray = [];
if(myArray.length === 0){
console.log("Array is empty", myArray)
}
</script>
</body>
</html>
Output:
Check if an array is empty or exists
if (typeof image_array !== 'undefined' && array.length > 0) {
// the array is defined and has at least one element
}
Do the check for undefined
first. If you do it the another way, it will generate an error if the array is undefined.
if (array === undefined || array.length == 0) {
// array empty or does not exist
}
It’s important to check for undefined before performing any operations on an array to avoid errors. This is especially crucial when accessing array elements or using array methods.
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