Use null coalescing operator

Use Null Coalescing (??)

You can even chain! The code skips the left side until it is null/undefined.

Null Coalescing Operator (??) covers cases where the left-hand side is:

null (LWC ; Apex) undefined (LWC)

javascript
function getUserLanguage() {
    return currentUser.preferredLanguage ?? 'en_US';
}

Why is it useful?

Replace IF-ELSE structures with one line of code.

Don't do this
function getUserLanguage() {
    if (currentUser.preferredLanguage) {
        return currentUser.preferredLanguage;
    }
    return 'en_US';
}
Do this
function getUserLanguage() {
    return currentUser.preferredLanguage ?? 'en_US';
}

You can even chain! The code skips the left side until it is null/undefined.

Do this
function getUserLanguage() {
    return currentUser.preferredLanguage ?? organization.language ?? 'en_US';
}

Apex

The ?? operator returns the left-hand argument if the left-hand argument isn’t null. Otherwise, it returns the right-hand argument. Similar to the safe navigation operator (?.), the null coalescing operator (??) replaces verbose and explicit checks for null references in code.

Don't do this
public static String getUserLanguage() {
    if (currentUser.preferredLanguage == null) {
        return 'en_US';
    }
    return currentUser.preferredLanguage;
}
Do this
public static String getUserLanguage() {
    return currentUser.preferredLanguage ?? 'en_US';
}

Lightning Web Components

The nullish coalescing (??) operator is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand

Don't do this
function getUserLanguage() {
    if (currentUser.preferredLanguage) {
        return currentUser.preferredLanguage;
    }
    return 'en_US';
}
Do this
function getUserLanguage() {
    return currentUser.preferredLanguage ?? 'en_US';
}

Text and code were extracted from the original slide. Plain-text version of the whole catalog