In JavaScript, checking if a variable is null or undefined can be achieved through several different methods. The following sections introduce commonly used approaches with examples:
1. Direct Comparison
You can directly use === (strict equality operator) to verify if a variable is null or undefined.
javascriptlet value; // Check if it is undefined if (value === undefined) { console.log('Variable is undefined'); } // Set the variable to null value = null; // Check if it is null if (value === null) { console.log('Variable is null'); }
2. Using typeof to Check
For undefined, you can use the typeof operator to check.
javascriptlet value; if (typeof value === 'undefined') { console.log('Variable is undefined'); }
However, note that typeof returns "object" for null, so it is not suitable for checking null.
3. Using == for Loose Comparison
If you want to check if a variable is neither null nor undefined, you can use == because it performs type coercion during comparison.
javascriptlet value; if (value == null) { console.log('Variable is null or undefined'); }
This method detects both null and undefined because in JavaScript, null == undefined evaluates to true.
4. Using Logical Operators
Logical operators in JavaScript (such as || and &&) are highly useful when handling null and undefined, particularly for setting default values or in chained calls.
javascriptlet value; let defaultValue = 'default value'; // If value is null or undefined, use default value let result = value || defaultValue; console.log(result); // Outputs 'default value'
These are several methods to check for null and undefined in JavaScript. In practice, selecting the appropriate method based on specific requirements is essential.