The JavaScript primitive type null
represents an intentional absence of a value. It’s usually set on purpose to indicate that a variable has been declared but not yet assigned any value.
null
is different 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
.
4 JavaScript (JS) Check for Null Methods
- Double Equality Operator
==
: Otherwise known as the loose equality operator, use this method to check if a value is loosely equal to null. - Triple Equality Operator
===
: Also known as the strict equality operator, use this method to make sure you have exactly a null value, excluding any undefined values - Logical NOT Operator
!
: This method works because empty objects are truthy and null is the only falsy object. Object.is()
: This is the helper method for changes of state in React, and it operates similar to the===
operator.
Unfortunately, typeof
returns “object”
when called on a null
value due to a historical bug in JavaScript that will never be fixed.
That means checking for null can’t be performed using typeof
. Null
is also a falsy value. If it’s coerced to a boolean, it will evaluate as false.
When to Check for Null in JavaScript
The TypeError, “null
is not an object”, can occur if the document object model (DOM) elements haven’t been created before loading the script. This can happen when the script is higher than the HTML on the page, which is interpreted from top-to-bottom.
While the solution would be to use an event listener that will notify us when the page is ready and then run the script, it’s also prudent to check if the DOM element is null
before trying to access it.
How to Check for Null in JavaScript (JS)
To determine whether a value is specifically null
, the triple equality operator is the best method available. We can also use this in conjunction with Object.is()
to determine a null value. Here’s a quick overview of both approaches.
Triple Equality Operator ===
To make sure we have exactly a null
value excluding any undefined
values, we can use the triple equality ===
operator, otherwise known as the strict equality operator:
console.log("The value null")
console.log(null===0) // false
console.log(null===0n) // false
console.log(null===null) // true
console.log(null===undefined) // false
console.log(null===false) // false
console.log(null===NaN) // false
console.log(null==="") // false
Generally, it’s 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 ==
(more on the double equality operator further down) is recommended. Otherwise, ===
is generally recommended.
Object.is() and Equality Operators
The JavaScript ES6 function Object.is()
checks for whether two values are the same rather than checking directly for null
. But you can use ==
or ===
to check specifically for null
. Object.is()
also differs from the strict ===
and double ==
equality operators in how it checks for NaN
and negative zero -0
.
For null
, the behavior of Object.is()
is the same as ===
:
let maybeNull = null
// The following is equivalent to maybeNull == null or maybeNull == undefined:
console.log(Object.is(maybeNull,undefined) || Object.is(maybeNull,null)) // true
// Compare to the following:
console.log(maybeNull == null) // true
console.log(maybeNull == undefined) // true
console.log(maybeNull === null) // true
console.log(Object.is(maybeNull,null)) // true
console.log(maybeNull === undefined) // false
console.log(Object.is(maybeNull,undefined)) // false
maybeNull = undefined
console.log(maybeNull === undefined || maybeNull === null) // true
console.log(maybeNull == null) // true
console.log(maybeNull == undefined) // true
console.log(maybeNull === null) // false
console.log(Object.is(maybeNull,null)) // false
console.log(maybeNull === undefined) // true
console.log(Object.is(maybeNull,undefined)) // true
Again, 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.
How to Check for Values Loosely Equal to Null in JavaScript (JS)
The following methods do not directly check for null
. Instead, they determine factors like falsiness or whether two values are the same. Still, these approaches are effective ways of checking for null
— sometimes they just require an additional method to complete the necessary steps.
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 doesn’t differentiate null
from the other falsy values, meaning false positives can arise. Still, this is a popular method that people like to use when checking for null:
const maybeNull = null
if(maybeNull) { console.log("Not null") } else { console.log("Could be null") } // Could be null
for(let i = 0; null; i++) { console.log("Won't run") }
maybeNull ? console.log("truthy value") : console.log("Falsy value") // falsy value
Let’s explore using the double equality ==
and triple equality ===
equality operators to check for null
.
Double Equality Operator ==
The double equality ==
operator confirms the absence of any value and does not directly check for null
. But one way to check for null
in JavaScript is to check if a value is loosely equal to null
using the double equality ==
operator:
console.log("The 7 falsy values")
0 ? console.log("truthy") : console.log("falsy") // falsy
0n ? console.log("truthy") : console.log("falsy") // falsy
null ? console.log("truthy") : console.log("falsy") // falsy
undefined ? console.log("truthy") : console.log("falsy") // falsy
false ? console.log("truthy") : console.log("falsy") // falsy
NaN ? console.log("truthy") : console.log("falsy") // falsy
"" ? console.log("truthy") : console.log("falsy") // falsy
console.log("The value null")
console.log(null==0) // false
console.log(null==0n) // false
console.log(null==null) // true
console.log(null==undefined) // true
console.log(null==false) // false
console.log(null==NaN) // false
console.log(null=="") // false
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 and are loosely equal, meaning 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
.
Double Equality == vs. Triple Equality === Operators
Some JavaScript programmers prefer everything to be explicit, 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 ==
and ===
.
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 ==
:
let maybeNull = null
// The following is equivalent to maybeNull == null or maybeNull == undefined:
console.log(maybeNull === undefined || maybeNull === null) // true
// Compare to the following:
console.log(maybeNull == null) // true
console.log(maybeNull == undefined) // true
console.log(maybeNull === null) // true
console.log(maybeNull === undefined) // false
maybeNull = undefined
console.log(maybeNull === undefined || maybeNull === null) // true
console.log(maybeNull == null) // true
console.log(maybeNull == undefined) // true
console.log(maybeNull === null) // false
console.log(maybeNull === undefined) // true
It’s more verbose than the ==
operator, but everyone who reads your code will clearly know that both null
and undefined
are being checked for.
Typeof and logical NOT !
Another method of checking for null
is to use the logical NOT !
operator and combine it with typeof
. This works because empty objects are truthy and null
is the only falsy object:
// The value null is the only falsy value with the typeof "object":
console.log(typeof null === "object" && !null) // true
console.log(typeof {} === "object" && !{}) // false
// This can be used to create a simple isNull() function:
const isNull = (value) => typeof value === "object" && !value
console.log(isNull(null)) // true
// To also check for an undeclared value, which will have typeof undefined, tweak the comparison slightly:
console.log(typeof maybeUndeclared === "undefined" || (typeof maybeUndeclared === "object" && !maybeUndeclared))
const isNullOrUndeclared = (value) => typeof value === "undefined" || (typeof value === "object" && !value))
const isNullOrUndeclared(undeclaredVariable) // true
// Otherwise, referencing an undeclared variable will throw a ReferenceError:
try { undeclaredVariable == null } catch(e) { console.log(e) } // ReferenceError: undeclaredVariable is not defined
Using typeof
can be a helpful trick, because if a variable is undeclared, trying to reference it will throw a ReferenceError
. However, the typeof
an undeclared value is "undefined"
, so using typeof
can be a good way to check for null
, undefined
and undeclared
variables.
It’s important to keep in mind that the logical NOT !
operator on its own only checks for falsiness. To check for null
specifically, you’ll need to use other methods like typeof
.
// This will safely check a value to make sure it has been declared and assigned a value other than null or undefined:
console.log(typeof undeclaredVariable !== "undefined" &&
(typeof undeclaredVariable !== "object" || !undeclaredVariable)) // false
// Compare to checking for null using ==, which will only work for declared variables:
try { undeclaredVariable == null } catch(e) { console.log(e) } // ReferenceError: undeclaredVariable is not defined
try { undeclaredVariable === null } catch(e) { console.log(e) } // ReferenceError: undeclaredVariable is not defined
try { undeclaredVariable === undefined } catch(e) { console.log(e) } // ReferenceError: undeclaredVariable is not defined
let declaredButUndefinedVariable
// Values that have been declared but not assigned a value will have the value undefined, which has a typeof undefined:
console.log(typeof declaredButUndefinedVariable !== "undefined" &&
(typeof declaredButUndefinedVariable !== "object" || !declaredButUndefinedVariable)) // false
let stringVariable = "Here's Johnny!"
// If the variable has been both declared and assigned a value that is neither null or undefined, we will get true:
console.log(typeof stringVariable !== "undefined" &&
(typeof stringVariable !== "object" || !stringVariable)) // true
// This can be used to create a function that will return false for undefined, undeclared, and null values:
const isNotNullNorUndefined = (value) => typeof value !== "undefined" && (typeof value !== "object" || !value)
console.log(isNotNullNorUndefined(stringVariable)) // true
Optional Chaining (?.) Operator and Strict Equality Operator
If you’re dealing with nested objects when checking for a null value, the optional chaining (?.) operator is an ideal approach. Optional chaining makes it easy to access properties of an object, even when intermediate properties may be null
or undefined
.
When navigating deeply nested objects, more traditional methods may throw an error if an intermediate object is null
or undefined
. But the optional chaining (?.) operator will immediately stop if it comes across a null or undefined property — a process known as short-circuiting — and produce the result “undefined.” This saves a lot of time and simplifies the expression, leading to much more readable code.
However, this method doesn’t distinguish between null
or undefined
, meaning it doesn’t directly check for null
either. To check for null
, you must compare the result of optional chaining with null
and undefined
via the strict equality operator.
Let’s take a look at an example involving someone’s basic information:
const user = {
profile: {
name: "Alice",
age: 30
}
};
console.log(user?.profile?.name); // Output: "Alice"
console.log(user?.contact?.email); // Output: undefined (instead of throwing an error)
In this case, user?.profile?.name
safely accesses name
inside profile
. Since profile
exists, it retrieves "Alice"
.
Then, user?.contact?.email
checks if contact
exists in user
. Since contact
is undefined
, it returns undefined
instead of throwing an error.
Without optional chaining, accessing user.contact.email
would cause an error if contact
is undefined
:
console.log(user.contact.email); // TypeError: Cannot read properties of undefined
To check if contact
is, in fact, null
rather than simply undefined
, use the strict equality operator to compare the result to null
and undefined
.
Why Check for Null in JavaScript?
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 to see 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
:
typeof maybeUndeclared !== "undefined" && (typeof maybeUndeclared !== "object" || !maybeUndeclared)
Now go out there and check for null
with confidence.
Frequently Asked Questions
What is a null check?
In JavaScript, null represents an intentional absence of a value, indicating that a variable has been declared with a null value on purpose. On the other hand, undefined represents the absence of any object value that is unintentional. A null check determines whether a variable has a null value, meaning a valid instance of a type exists.
Is null false in JavaScript?
Null is not considered false in JavaScript, but it is considered falsy. This means that null is treated as if it’s false when viewed through boolean logic. However, this is not the same thing as saying null is false or untrue.
What is a strict null check?
StrictNullChecks is a feature that treats null and undefined as two separate types, reducing errors and making it easier to find coding bugs. It also has stronger measures for defining variables as null or undefined, ensuring variables are declared as null only when it’s safe to do so.