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)
function getUserLanguage() {
return currentUser.preferredLanguage ?? 'en_US';
}Why is it useful?
Replace IF-ELSE structures with one line of code.
function getUserLanguage() {
if (currentUser.preferredLanguage) {
return currentUser.preferredLanguage;
}
return 'en_US';
}function getUserLanguage() {
return currentUser.preferredLanguage ?? 'en_US';
}You can even chain! The code skips the left side until it is null/undefined.
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.
public static String getUserLanguage() {
if (currentUser.preferredLanguage == null) {
return 'en_US';
}
return currentUser.preferredLanguage;
}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
function getUserLanguage() {
if (currentUser.preferredLanguage) {
return currentUser.preferredLanguage;
}
return 'en_US';
}function getUserLanguage() {
return currentUser.preferredLanguage ?? 'en_US';
}

