In JavaScript, null
is a primitive value intended to represent the purposeful absence of any value for a given object.
If you call a variable and it has the value null
, this means that the variable has been declared, but no data has been assigned to it. Simply put, it’s like an empty placeholder for data.
Check If a Variable Is Null
The best way to check if a variable is null
in JavaScript is using an if
statement with the strict equality operator (===
).
if (myVariable === null) {
/* Do this if variable is null */
}
Don’t use the equality operator (=
) because it can return false positives when the value of your variable is false
, 0
, ""
(an empty string), null
, undefined
, or NaN
. The strict equality operator (===
) doesn’t have this problem because it checks against the value and the type of the two operands.
Check If a Variable Is Not Null
The best way to check if a variable is not null
in JavaScript is using an if
statement with the strict inequality operator (!==
).
if (myVariable !== null) {
/* Do this if variable is not null */
}
Don’t use the inequality operator (!=
) because it can return false positives when the value of your variable is not false
, 0
, ""
(an empty string), null
, undefined
, or NaN
. The strict inequality operator (!==
) doesn’t have this problem because it checks against the value and the type of the two operands.