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 null and undefined to compare outcomes since they are sometimes confused because of their similarities.
//declaring two variables: one null and one undefined. let leviticus = null; // leviticus is null let dune; // dune is undefined
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 typeof()
You can check for null with the
// typeof() will return 'object' when called on a null variable console.log(typeof(leviticus)) // object console.log(typeof(dune)) // undefined
Curiously, if you check with
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: twitter.com/EamonnCottrell
Have a great one 👋.