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
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.