To check if an array is empty, NULL, or undefined in jQuery and JavaScript, we use two major functions,
- jQuery.isEmptyObject(arrayVariable)
- length property
To check, if an array is undefined we use typeof
JS operator. And by using jQuery of JS length property we can check the length of the array, to check if it is empty or not.
Here we can check multiple examples, that show how we can check if an array is empty.
And if not how can I loop through the complete array of data with their keys?
Example-1 By using the JS length property
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
var testArray=[1,2,3,4,5]; //get all array values if not empty $.each(testArray, function( index, value ) { if (value) { console.log(index + ": " + value); } }); //Here we check the length of an array if (testArray.length === 0) { console.log("Array is empty."); } else { console.log("Array is not empty."); } |
In the above example, first, we have defined a non-empty array, and by using jQuery each function loop through all the array values.
At last, by using the array length property we have checked whether an array is empty or not.
Output:
Example-2 By using isEmptyObject jQuery function
1 2 3 4 |
var testArray=[1,2,3,4,5]; var testArray1=[]; console.log(jQuery.isEmptyObject(testArray)); //false console.log(jQuery.isEmptyObject(testArray1)); //true |
Here also we have just defined two arrays, one is non-empty, and the second is an empty array.
And by using jQuery.isEmptyObject
the function we can check if an array is empty or NULL.
Output:
false
true
Example-3 By using if-else condition and typeof
JS operator
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
/* Basic Checking with empty array for Jquery Array */ var myArray2 = []; if (myArray2 && myArray2.length > 0) { console.log('myArray2 is not empty.'); }else{ console.log('myArray2 is empty.'); } /* Basic Checking with undefined array for Jquery Array */ if (typeof myArray3 !== 'undefined' && myArray3.length > 0) { console.log('myArray3 is not empty.'); }else{ console.log('myArray3 is empty.'); } /* Basic Checking with null array for Jquery Array */ var myArray4 = null; if (myArray4 && myArray4.length > 0) { console.log('myArray4 is not empty.'); }else{ console.log('myArray4 is empty.'); } |
Output:
myArray2 is empty.
myArray3 is empty.
myArray4 is empty.
Conclusion
In this article, we have learned complete knowledge about how we can check if an array is empty, NULL, or undefined programmatically.
Also, you can check the complete concept via multiple running examples. You can run those examples on JS online compilers like JSFiddle – Code Playground.
I hope you understand the complete concept and implementation. Let me know if you are facing any issues.
[…] How to check if an array is empty, NULL, or undefined in jQuery? January 21, 2022 […]
[…] How to check if an array is empty, NULL, or undefined in jQuery? January 21, 2022 […]