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:
|
1 2 3 |
let age: number | null age = setAge(personId) |
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:
|
1 2 3 4 5 6 7 |
const getPersonType(age: number) { if(!age) return 'unknown' if(age === 0) return 'new born' if(age <= 3) return 'infant' if(age > 3) return 'other' } |
There is a problem with this code. This clause is actually redundant:
|
1 |
if(age === 0) return 'new born' |
because it is preceded by this clause:
|
1 |
if(!age) return 'unknown' |
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:
|
1 |
if(age == null) return 'unknown' |