`Array.isNotEmpty` to check array status easily

A very common situation is to check param is both Array and not empty before loop.

Thanks to Array.isArray and we can do like this:

if(Array.isArray(list) && list.length > 0) {
   // do something
}

Although we can provide a common function to validate, a built-in method isNotEmpty may be more convenient.
isNotEmpty returns true when arg is both array and it has at least one element. Therefore, false means arg is not an array or array without any element.

a polyfill may like this:

if (!Array.isNotEmpty) {
  Array.isNotEmpty = function (arg) {
    return Array.isArray(arg) && arg.length > 0
  };
}
1 Like

There's no need to check if an array has content before looping over it. If the array is empty, then looping over it will cause the loop's body to be executed zero times, and nothing will happen.

Sorry for my vague description. I mean we may do some additional work before loop an array only if it has elements.
Of cause we can use list?.map or other methods safely.

2 Likes

For reference Lodash's isEmpty gets almost 1.5 million downloads a week.

That does a bit more, though. Notably, it can tell you if an object lacks own properties as a fallback when no size or length property exists. (I have my own preference for that, though.)

1 Like

Please don't test a negative.

[].concat(x).length === 0

until people start throwing Symbol.isConcatSpreadable on x...