1if (typeof array !== 'undefined' && array.length === 0) {
2 // the array is defined and has no elements
3}
4
1// To safely test if the array referenced by variable “array” isn’t empty:
2
3if (array && array.length) {
4 // not empty
5} else {
6 // empty
7}
8// Note that if “array” is assigned to some other object that isn’t an array, the code will still execute the “else” part.
9
10// A possible improvement to check that the object is specifically an empty array might be this:
11
12if (array && array.constructor === Array && array.length === 0) {
13 // strictly an empty array
14} else {
15 // either null, or not an array or not an empty array
16}
1let myArray = [];
2
3if( myArray.length > 0 ) {
4 console.log(myArray);
5 console.log("Array has elements");
6}
7else {
8 console.log("Array has no elements");
9}