How to check if array is empty or null or undefined in javascript?
Syntax Code
if (productInfoArr && productInfoArr.length > 0) { console.log('productInfoArr is not empty.'); }else{ console.log('productInfoArr is empty.'); }
Example:
<!DOCTYPE html> <html> <head> <title>How to check if array is empty or null or undefined in javascript? - ItSolutionStuff.com</title> </head> <body> <script type="text/javascript"> /* Basic Checking for Jquery Array */ var productInfoArr = [1, 2, 3]; if (productInfoArr && productInfoArr.length > 0) { console.log('productInfoArr is not empty.'); }else{ console.log('productInfoArr is empty.'); } /* Basic Checking with empty array for Jquery Array */ var productInfoArr2 = []; if (productInfoArr2 && productInfoArr2.length > 0) { console.log('productInfoArr2 is not empty.'); }else{ console.log('productInfoArr2 is empty.'); } /* Basic Checking with undefined array for Jquery Array */ if (typeof productInfoArr3 !== 'undefined' && productInfoArr3.length > 0) { console.log('productInfoArr3 is not empty.'); }else{ console.log('productInfoArr3 is empty.'); } /* Basic Checking with null array for Jquery Array */ var productInfoArr4 = null; if (productInfoArr4 && productInfoArr4.length > 0) { console.log('productInfoArr4 is not empty.'); }else{ console.log('productInfoArr4 is empty.'); } </script> </body> </html>
Results
productInfoArr is not empty. productInfoArr2 is empty. productInfoArr3 is empty. productInfoArr4 is empty.