Is anything truly empty?
debadeepsen
Posted on July 2, 2021
I decided to write this series because there are parts of JavaScript that feel right, but aren't. Or feel wrong, but are perfectly acceptable, and they can cause common mistakes that could potentially lead to hours of wasted time in unproductive debugging. This is the first of hopefully multiple posts, explaining such concepts, so that you don't fall into one of these traps ever (again).
Empty array is truthy
Consider the following code:
function checkTruthy(o) {
if (o) console.log("truthy");
else console.log("not truthy");
}
let s = "";
let t = 0;
let u = [];
checkTruthy(s);
checkTruthy(t);
checkTruthy(u);
So we have an empty string, the number zero, and an empty array. Similar things, right? So what do you expect the output to be? If you guessed anything other than the one below, you're wrong.
not truthy
not truthy
truthy
That is correct, the empty array is truth-like, and as such, any check that looks like if(empty_array)
will return true
. This can be extremely important when what you really need to check for is the emptiness of said array. In such cases, remember to modify your if
statements like so -
if(my_array && my_array.length) {
// stuff and things
}
What it really checks is if the array variable is
undefined
or not. That is why the code above also lets you avoid unwanted runtime exceptions.
Oh, and btw? I hope this doesn't blow your mind but you know what makes the empty array non-truthy? A simple negative sign before it. That's right, if(-[])
will never execute, its else block (if it exists) will instead.
[Photo from Pixabay/Pexels]
Posted on July 2, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.