
Introduction
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.
Checking for undefined or null
Direct Comparison Using Strict Equality
Declare a variable without assigning a value or explicitly set it to
null.Use the strict equality operator (
===) to compare the variable withundefinedandnull.javascriptlet 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
undefinedornull. The results aretrueif the comparisons match exactly, illustrating thataisundefinedandbisnull.
Using the Typeof Operator for undefined
Check if a variable is
undefinedby using thetypeofoperator.Compare the result of
typeofwith the string'undefined'.javascriptlet c; console.log(typeof c === 'undefined'); // true
The
typeofoperator returns'undefined'if the variable has not been assigned a value. This method is exclusively reliable for checkingundefinedbecausenullis of type'object'.
Combining Checks for Both Conditions
Combine conditions using logical OR (
||) to check if a variable is eitherundefinedornull.Use direct comparison for both
undefinedandnull.javascriptlet d; let e = null; console.log(d == null); // true console.log(e == null); // true
Here, the loose equality operator (
==) checks for bothundefinedandnullwithout having to use two separate strict equality checks. It's a concise way to check for the absence of a value, treating bothundefinedandnullas equivalent.
Conclusion
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.