Determining if a variable in JavaScript is undefined
or null
is a common check required in many programming scenarios, from validating function arguments to handling API response data. These checks help in ensuring that the program behaves as expected without running into runtime errors due to unexpected absence of values.
In this article, you will learn how to check if a variable is undefined
or null
in JavaScript through practical examples. Explore simple yet effective ways to prevent errors and enhance the reliability of your JavaScript code.
Declare a variable without assigning a value or explicitly set it to null
.
Use the strict equality operator (===
) to compare the variable with undefined
and null
.
let a;
let b = null;
console.log(a === undefined); // true
console.log(b === null); // true
console.log(a === null); // false
console.log(b === undefined); // false
Here, the strict equality operator checks whether a variable precisely holds undefined
or null
. The results are true
if the comparisons match exactly, illustrating that a
is undefined
and b
is null
.
undefined
Check if a variable is undefined
by using the typeof
operator.
Compare the result of typeof
with the string 'undefined'
.
let c;
console.log(typeof c === 'undefined'); // true
The typeof
operator returns 'undefined'
if the variable has not been assigned a value. This method is exclusively reliable for checking undefined
because null
is of type 'object'
.
Combine conditions using logical OR (||
) to check if a variable is either undefined
or null
.
Use direct comparison for both undefined
and null
.
let d;
let e = null;
console.log(d == null); // true
console.log(e == null); // true
Here, the loose equality operator (==
) checks for both undefined
and null
without having to use two separate strict equality checks. It's a concise way to check for the absence of a value, treating both undefined
and null
as equivalent.
Checking if a variable is undefined
or null
is essential for writing robust JavaScript code. By using strict equality checks, the typeof
operator, and combined conditions, you effectively safeguard your application against unexpected behaviors caused by undefined or null values. Implement these methods to ensure that your applications handle such cases gracefully and continue to function correctly even when encountering missing or incomplete data.