Javascript – get acquainted with falsy

If you are not aware of what the exact definition of Falsy is in Javascript, then I recommend patching that knowledge gap immediately. Here is the definition.

I want to highlight why it is important to have a full grasp of this concept. Consider this code:

Here we have an age variable and we expect that it can either be a number or null. Next we want to set a variable that holds the person type, if the person is age 0 they are a new born, if they are aged 1-3 they are an infant, and any older is other. If we get a null we will set the type as unknown.

Let’s try to code this:

There is a problem with this code. This clause is actually redundant:

because it is preceded by this clause:

as 0 (zero) is actually falsy, so when we want to get the value of new born, we would actually get unknown, now you have a bug in your system because you didn’t take the time to know Falsy 🙂

And in this scenario we can easily fix this by making our first check more specific: