Let’s now take a look into what that means, what nullish is and how it compares to falsy and truthy values.
null. You can think of it in a similar way to how you would think of something that is either truthy or falsy.
Nullish is always a falsy value though so nullish is contained within falsy because both
null are both falsy values.
(If you are unfamiliar with truthy and falsy values, don’t worry I will cover them in the next section below.)
The times you might want to make use of nullish values are when you use the Nullish Coalescing Operator.
Here is a quick example of how this will look in JS:
null ?? "Hello World" // "Hello World" false ?? "Hello World" // false 0 ?? "Hello World" // 0 undefined ?? "Hello World" // "Hello World"
What are Falsy and Truthy values and how are they different from Nullish values?
This means that a boolean is always either truthy or falsy, but a truthy or falsy value is not always a boolean.
And anything that can be converted into false is a falsy value.
For example of double negation to create a boolean:
!!true // true !!false // false
Example of falsy values:
!!0 // false !!" // false !!10 // true !!"hello" // true
Truthy values on the other hand are the counterpart of falsy values meaning that everything is exactly the same except when you evaluate a value it will return true instead of false.
And anything that is not on that list is a truthy value.
So how do they differ from nullish values?
The reason why you can think of them in a similar way to falsy is because they also evaluate a subset of values to determine if they are nullish or not.
All this means is a nullish check is just a way to more specifically check if something is
undefined rather than just falsy.
For example, if you want a condition to pass if it is provided with any string, including empty strings and fail when it is provided with null or undefined then you might want to check for nullish values rather than falsy values because an empty string evaluates to false meaning it is falsy and would therefore fail the condition even though you want it to pass with an empty string.
However, if you checked for nullish values, because an empty string is not a nullish value it will still pass the condition.
Example with a falsy check:
null || "Did not pass" // "Did not pass" Undefined || "Did not pass" // "Did not pass" "" || "Did not pass" // "Did not pass"
Example with a nullish check:
null ?? "Did not pass" // "Did not pass" undefined ?? "Did not pass" // "Did not pass" "" ?? "Did not pass" // "" (this means it passed!)
So to summarize this all in a few words, Nullish is anything that is either
null, falsy is anything that evaluates to false, and truthy is anything that evaluates to true.