How to check for
Because of a historical bug,
What is null?
null from the similar primitive value
undefined , which is an unintentional absence of any object value. For example, a variable that has been declared but not assigned any value is
typeof returns “object” when called on a
That means checking for null can’t be performed using
null is falsy
The simplest way to check for
null is to know that
null evaluates to false in conditionals or if coerced to a
Of course, that does not differentiate
null from the other falsy values.
I explore using the
=== equality operators to do so next.
Falsy equality using ==
As shown above,
null is only loosely equal to itself and
undefined, not to the other falsy values shown.
This can be useful for checking for the absence of value —
undefined both indicate an absence of value, thus they are loosely equal (they have the same value even though they are different types).
So, when programming to check if a variable has any value at all before trying to process it, I can use
== null to check for either
Strict equality using
To make sure we have exactly a
null value, excluding any
undefined values, using the triple equality
=== operator will do the trick:
Generally, it is a good idea to catch both
== is recommended, while otherwise
=== is generally recommended.
A real world example of when to check for null
This TypeError (“null is not an object”) can occur if the DOM elements have not been created before loading the script, such as if the script higher than the HTML on the page, which is interpreted from top-to-bottom.
The solution would be using an event listener that will notify us when the page is ready, and then running the script.
But still, it might be prudent to check if the DOM element is
null before trying to access it.
Use typeof anyway with falsy power
An alternative method of checking for null is based on knowing that null is falsy, but empty objects are truthy, so null is the only falsy object.
The typeof keyword returns “object” for null, so that means a little bit more effort is required.
The value null is falsy, but empty objects are truthy, so
typeof null === “object” && !null is a convenient way to check for null.
Or, comparisons can be made:
null === null or
null == undefined.
Go out there and check for
null with confidence!
Rant.js — undefined vs null
Does it matter? They’re both falsy values that behave similarly, isn’t this a little silly? I don’t think so.
- Hackernoon author Yuri Ramos ‘s first tip shows how to check for null or undefined in one line using
let variable2 = variable1 || '':