1if (typeof array !== 'undefined' && array.length === 0) {
2 // the array is defined and has no elements
3}
4
1if (array === undefined || array.length == 0) {
2 // array empty or does not exist
3}
4
1if (Array.isArray(array) && array.length) {
2 // array exists and is not empty
3}
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}
1var colors=[];
2if(!colors.length){
3 // I am empty
4}else{
5 // I am not empty
6}