How to Check if an Array Is Empty in Javascript?

Check if a JavaScript array is empty

To check if a JavaScript array is empty or not, you can make either of the following checks (depending on your use case):

const empty = !Array.isArray(array) || !array.length;
const notEmpty = Array.isArray(array) && !!array.length;

This works in the following way:

  • In the first part of the logical expression, it checks strictly whether the operand is an array or not. At this point, it will exclude all non-array values, including array-like objects;
  • It only reaches the second part of the logical expression if the operand is indeed an array, and accordingly, it will check the length property to see if the array has any elements or not.

For non-empty check, casting to boolean (for example using double negation — i.e. !!) is not essential. However, it might be needed in situations where strict typing is expected. If you don't do this, the logical && operation will return the last value or the first falsy value.

For example:

const isEmpty = (arr) => !Array.isArray(arr) || !arr.length;
const hasElems = (arr) => Array.isArray(arr) && !!arr.length;

const arr = [];

console.log(isEmpty(arr)); // true
console.log(hasElems(arr)); // false

Consider the following example to see how this does not work for array-like objects (or other objects that may have the length property):

const arrLikeObj = { 0: 'foo', length: 1 };
console.log(isEmpty(arrLikeObj)); // true
console.log(hasElems(arrLikeObj)); // false

Hope you found this post useful. It was published . Please show your love and support by sharing this post.