Sometimes you’ve gotta check to make sure that nothing isn’t actually…nothing. 😲❗❓
So, null is nothing and undefined is just missing something. 🤣
Not super helpful, I know. Let’s dive deeper.
How to Define Null and Undefined Values
An example will help. Below we declare two variables. Let’s keep it simple and use
undefined to compare outcomes since they are sometimes confused because of their similarities.
leviticus is intentionally without an object value (null). Whereas
dune is declared, yet it’s unintentionally missing a value (undefined).
How to Check for Null with
You can check for null with the
Curiously, if you check with
typeof(), a null variable will return
How to Check for Null with Equality Operators
Another curiosity is that when you loosely check for equality using double equals
undefined will return
console.log(leviticus == dune) // true console.log(leviticus === dune) // false console.log(leviticus == null) // true (but not as good a habit to use as strict equality shown in next example)
But when you strictly check for equality using triple equals
===, null and undefined will return
false when encountered in a Boolean (
But by strictly checking for equality, you can see that they are in fact not equal.
How to to Check for Null with Strict Equality
The best way to check for null is to use strict and explicit equality:
console.log(leviticus === null) // true console.log(dune === null) // false
How to Check for Null with the
An equally foolproof way to check for null is to use the built-in
console.log(Object.is(leviticus, null) // true console.log(Object.is(dune, null) // false
nullis a primitive type of a variable which evaluates falsy, has a
typeof()of object, and is typically intentionally declared as
undefinedis a primitive type of a variable which evaluates falsy, has a
typeof()of undefined, and represents a variable that is declared but missing an initial value.
null == undefinedevaluates as true because they are loosely equal.
null === undefinedevaluates as false because they are not, in fact, equal.
<null_variable> === nullis the best way to strictly check for null.
Object.is(<null_variable>,null)is an equally reliable way to check for null.
Thanks for Reading!
I hope this was a helpful breakdown for you. Keep coding, and keep leaning forward!
Come say hey to me over on Twitter: https://twitter.com/EamonnCottrell
Have a great one 👋.