How to check if an array is empty or does not exist?
Here's the quick way to check array emptiness or non-existence:
This little piece of code uses the concept of logical short-circuiting. It checks if arr
is undefined
or null
, and arr.length
is zero. Both situations result in the generation of emptiness truthiness.
Is it an array, and is it non-empty?
Before answering, "Is the array empty?" let's ask, "Is it truly an array?" Here's how we do that:
The Array.isArray(arr)
function ensures arr
is indeed an array in disguise, preventing imposters (aka array-like objects) from passing the check.
If pragmatism is your mantra
There's an even more idiomatic and readable approach that uses optional chaining (invented, by the way, when JavaScript decided to simplify our lives with ECMAScript 2020):
Watch your step, undefined lurking!
This code snippet is the equivalent of "seeing the sign and not stepping on the banana peel." It prevents unforeseen accidents, such as TypeErrors.
Are you an equal(equal)ist?
For clarity and precision, use strict equality checks:
Strict equalities (===
, !==
), unlike abstract friends (==
, !=
), don't coerce types and hence are safer to use.
The art of choosing foolproof vs. pragmatic
Use a tighter, foolproof method for critical code sections. Otherwise, for falsy values implying emptiness, the more relaxed pragmatic method does the job well.
Array-like objects in disguise
Array.isArray()
does a great job, but remember it doesn't unmask array-like objects:
This vigilant function will prevent false positives and ensure only bona fide arrays (and object behaving like arrays) get past.
TypeScript's defensive stance
With TypeScript, no more cold nights worrying about potentially undefined variables:
In this TypeScript function, arr?
implies that arr
is optional and will be cared for as an array if provided.
Embrace the new age JavaScript
Finally, embracing new ECMAScript can result in cleaner and more intuitive syntax:
The arrow function with optional chaining makes the code Robocop sleek and efficient.
Deep dive: potential pitfalls and solutions
Let's be prepared for unpredictabilities that arrays might throw at you!
Sparse arrays: The missing elements
Sparse arrays are like Swiss cheese: They have "empty slots." Like this:
To handle sparse arrays, check for actual data presence:
Falsy values: A legitimate lie
Arrays can contain falsy values (0
, null
, ""
, etc.), which are still valid elements. Like this tricky fellow:
Our emptiness checks will rightfully consider this array non-empty. But depending on your context, you might need to treat falsy values specially.
Performance: Speed matters
Although these checks work fast, avoid redundancy. If you're checking array's emptiness in a loop, consider storing it in a variable:
Use utility functions: Because DRY
To avoid repetition, use utility functions for frequent checks:
Was this article helpful?