Borislav Hadzhiev
Fri Oct 15 2021·2 min read
Photo by Mantas Hesthaven
To check if a variable is null
or undefined
use the ||
(or) operator to
check if either of the two conditions is met. When used with two boolean values
the ||
operator returns true
if either of the conditions evaluate to
true
.
const age = null; // 👇️ Check if undefined or null if (age === undefined || age === null) { console.log('✅ variable is undefined or null'); } else { console.log('⛔️ variable is NOT undefined or null'); } // 👇️ Check if NOT undefined or null if (age !== undefined && age !== null) { console.log('✅ variable is NOT undefined or null'); }
Our first if
statement checks if the age
variable is either undefined
or
null
.
If either of the conditions is satisfied the if
block runs, otherwise the
else
block runs.
Our second if
statement checks if the variable is NOT equal to null
and is
not equal to undefined
.
For this example we use the logical
&& (and)
operator to specify that both conditions have to be met for the if
block to
run.
For all of the examples above we used
strict equality ===,
however there is a more concise way to check if a variable is equal to null
or
undefined
, using
loose equality ==.
To check if a variable is equal to null
or undefined
, use the loose
equality (==) operator. For example, age == null
returns true
if the
variable age is null
or undefined
. Comparing null
with undefined
using
the loose equality operator returns true
.
const age = undefined; if (age == null) { console.log('✅ variable is undefined or null'); } console.log(null == undefined); // 👉️ true
Because we use loose equality (==), the condition is met if the age variable is
either undefined
or null
.
This is a bit more implicit than using the strict equality operator and might be confusing to some developers reading your code.