Because of a historical bug, typeof null in JavaScript returns “object” ? so how do you check for null?
Photo by Ben Hershey on Unsplash
What is null?
?The value null represents the intentional absence of any object value. It is one of JavaScript’s primitive values.? ? MDN Docs
The JavaScript primitive type null represents an intentional absence of a value ? it is usually set on purpose to indicate that a variable has been declared but not yet assigned any value.
This contrasts null from the similar primitive value undefined , which is an unintentional absence of any object value.
That is because a variable that has been declared but not assigned any value is undefined, not null.
Unfortunately, typeof returns “object” when called on a null value, because of a historical bug in JavaScript that will never be fixed.
That means checking for null cannt be performed using typeof.
Photo by Eugene Triguba on Unsplash
null is falsy
?null is a falsy value (i.e. it evaluates to false if coerced to a boolean)? ? Josh Clanton at A Drip of JavaScript
The simplest way to check for null is to know that null evaluates to false in conditionals or if coerced to a boolean value:
Of course, that does not differentiate null from the other falsy values.
Next, I explore using the == or === equality operators to check for null.
Photo by Nicholas Ruggeri on Unsplash
Falsy equality using ==
?Despite the fact that null is [falsy], it isn’t considered loosely equal to any of the other falsy values in JavaScript. In fact, the only values that null is loosely equal to are undefined and itself.? ?Josh Clanton at A Drip of JavaScript
One way to check for null in JavaScript is to check if a value is loosely equal to null using the double equality == operator:
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 ? null and 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, you can use == null to check for either null or undefined.
Photo by David Becker on Unsplash
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 null and undefined values, as both represent an absence of a value.
That means checking for null is one of the few times in JavaScript that using == is recommended, while otherwise === is generally recommended.
Photo by Dan Meyers on Unsplash
Comparing == vs === when checking for null
Some JavaScript programmers prefer everything to be explicit for clarity, and there is nothing wrong with that.
Indeed, the code linter JSLint explicitly disallows == to prevent accidental bugs resulting from type coercion.
Another popular code linter, ESLint, has similar but more-configurable behavior around the use of == vs. ===.
That means that if you (or your linter) are in the habit of always using the strict equality operator ===, then you can check whether a value strictly equals null OR (||) strictly equals undefined instead of using ==:
It is more verbose than the == operator, but everyone who reads your code will clearly know that both null and undefined are being checked for.
Photo by Cassie Boca on Unsplash
A real world example of when to check for null
?One way this error [?null is not an object?] might occur in a real world example is if you try using a DOM element in your JavaScript before the element is loaded. That?s because the DOM API returns null for object references that are blank.? ? Rollbar on the Top 10 JavaScript errors
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.
Photo by Denys Nevozhai on Unsplash
Use typeof anyway with falsy power
?Thankfully since null isn?t really an object, it?s the only ?object? that is a falsy value, empty objects are truthy.? ? Casey Morris in Daily JS
Another method of checking for null is based on the fact that null is falsy, but empty objects are truthy, so null is the only falsy object.
This can be conveniently checked using the logical NOT ! operator:
Using typeof can be a helpful trick, because if a variable is undeclared, then trying to reference it will throw a ReferenceError.
But, the typeof an undeclared value is undefined, so using typeof can be a good way to check for null, undefined, and undeclared variables.
Photo by Dylan Freedom on Unsplash
Using Object.is()
The ES6 function Object.is() differs from the strict === and loose == equality operators in how it checks for NaN and negative zero -0.
For null, the behavior of Object.is() is the same as ===:
That means that you will need to explicitly check for both null and undefined if you are using Object.is(), which is the helper method checking for changes in state under the hood in React.
Photo by Patrick Hendry on Unsplash
Conclusion
Checking for null is a common task that every JavaScript developer has to perform at some point or another.
The typeof keyword returns “object” for null, so that means a little bit more effort is required.
Comparisons can be made: null === null to check strictly for null or null == undefined to check loosely for either null or undefined.
The value null is falsy, but empty objects are truthy, so typeof maybeNull === “object” && !maybeNull is an easy way to check that a value is not null.
Finally, to check if a value has been declared and assigned a value that is neither null nor undefined, use typeof:
Now go out there and check for null with confidence!
Photo by Puk Patrick on Unsplash
Additional resources
- Konstantin Blokhin cleans up ?null check pollution? at freeCodeCamp:
How to avoid null check pollution in JavaScript: use Optionals
by Konstantin Blokhin How to avoid null check pollution in JavaScript: use Optionals Wash your code?
www.freecodecamp.org
- Casey Morris has some opinions about null and undefined on DailyJS:
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.
medium.com
- Abinav Seelan explains why null >= 0 is true over on Camp Vanilla:
Javascript : The Curious Case of Null >= 0
Why it?s important to read the Javascript Spec
blog.campvanilla.com
- Kiro Risk has an article about null and typeof in JavaScript Refined:
Null and typeof
Demystifying typeof null, once and for all
javascriptrefined.io
- Hackernoon author Yuri Ramos ?s first tip shows how to check for null or undefined in one line using let variable2 = variable1 || ”:
12 Good JavaScript Shorthand Techniques
Update 1: Due to a lot of polarizing comments (like loved or hated the article) I just want to be clear that shorthand?
hackernoon.com
- Alex Ellis did a deep dive into why typeof null is bugged on his blog:
typeof null: investigating a classic JavaScript bug
In my last post, I looked into some JavaScript casting and explored why 0 <= null evaluates as true. For this post, I?d?
alexanderell.is
Photo by Toby Christopher on Unsplash