JavaScript Program to Check If A Variable Is undefined or null

Updated on November 6, 2024
Check if a variable is undefined or null header image

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

  1. Declare a variable without assigning a value or explicitly set it to null.

  2. Use the strict equality operator (===) to compare the variable with undefined and null.

    javascript
    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.

Using the Typeof Operator for undefined

  1. Check if a variable is undefined by using the typeof operator.

  2. Compare the result of typeof with the string 'undefined'.

    javascript
    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'.

Combining Checks for Both Conditions

  1. Combine conditions using logical OR (||) to check if a variable is either undefined or null.

  2. Use direct comparison for both undefined and null.

    javascript
    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.

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.