If you are a web developer( now almost everywhere), you might have encountered this question already , how to check if array is empty or null or undefined in JavaScript?. Like other programming languages, JavaScript also have methods to check this.
The simplest would be
let myArray = []; if( myArray.length > 0 ) { console.log(myArray); console.log("Array has elements"); } else { console.log("Array has no elements"); }
But here is a problem if the array is not defined as an empty array initially, this will throw an error.
To overcome that we can use the below script, will be good fit for most of the cases.
//let myArray = []; if( typeof myArray != 'undefined' && myArray.length > 0 ) { console.log(myArray); console.log("Array has elements"); } else { console.log("Array has no elements"); }
Again if the myArray =null
, then this will throw an another error like – can not read the length property on null. So our below code will cover this as well.
let myArray = null; if( myArray && typeof myArray != 'undefined' && myArray.length > 0 ) { console.log(myArray); console.log("Array has elements"); } else { console.log("Array has no elements"); }
- Just want to thank us? Buy us a Coffee
- May be another day? Shop on Amazon using our links.
Your prices won't change but we get a small commission.
Leave a Reply