乐闻世界logo
搜索文章和话题

JavaScript checking for null vs. Undefined

1个答案

1

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.

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

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

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

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

2024年6月29日 12:07 回复

你的答案