SoFunction
Updated on 2025-04-06

Common ways to deal with null and undefined in JavaScript

1. Optional chain operator (?.)

const user = {
    address: {
        city: "Beijing"
    }
};
(?.city); // Output "Beijing"(?.city); // Output undefined

When the chain cannot find the next property, undefined will be returned

2. Null value merging operator (??)

When the left value of ?? is null or undefined, the default value on the right will be taken

(null ?? "default"); // Output "default"(undefined ?? "default"); // Output "default"("Hello" ?? "default"); // Output "Hello"("" ?? "default"); // Output ""(0 ?? "default"); // Output 0(false ?? "default"); // Output false(false || "default"); // Output default

Pay attention to the difference between ?? and ||
??: Just innullandundefinedReturn defaultValue
||: Not only will it benullandundefinedWhen returning defaultValue, it will also be infalse, 0, ''Return the default value defaultValue under other false values ​​such as (empty string)

3. Optimization judgment

Generally speaking, it's a judgmentifWhen a statement,There are often similar judgments。
if( === undefined ||  === null ||  === ''){
}

Yes, this judgment can be optimized by using a more concise and readable way. Here are several common optimization methods:

3.1 Use == for loose comparison

Use loose equality operator==Can check at the same timeundefinedandnull

if ( == null ||  === '') {
    // Processing logic}

3.2 Use logical non-operators!

Logical non-operators can be used!Check the falsy value (e.g.undefinednull''0NaNandfalse):

if (!) {
    // Processing logic}

However, be aware that this way will treat all false values ​​astrue, if you need to exclude0orfalse, it does not apply.

3.3 Use optional chain and null value merging operators

Combining optional chain operators and null value merging operators can be more concise:

if (?.trim() === '') {
    // Processing logic}

3.4 Using custom functions

If this check is used in multiple places, consider encapsulating it into a function:

function isEmpty(value) {
    return value == null || value === '';
}
if (isEmpty()) {
    // Processing logic}

Summarize

Which method to choose depends on the specific requirements and context. use!Operators are the most concise, but they need to be sure that other falsy values ​​are not misjudged. If stricter inspection is required, use==Or a custom function might be more suitable.

This is the article about the analysis of handling null and undefined situations in JavaScript. For more related content on handling null and underfined by JS, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!