---
title: "Use null coalescing operator"
url: "https://blog.beyondthecloud.dev/tips/use-null-coalescing-operator"
category: "LWC"
tags: "apex"
published: "2024-04-02"
---

# Use null coalescing operator

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

### Use Null Coalescing (??)

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.

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

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

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

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

```apex
public static String getUserLanguage() {
    if (currentUser.preferredLanguage == null) {
        return 'en_US';
    }
    return currentUser.preferredLanguage;
}
```

```apex
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

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

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