Why Is the Nullish Coalescing Operator(??) Essential in JavaScript?
Tags: javascript, webdev, beginners, programming
Published: 2023-11-09 12:55:10

As JavaScript developers, we've all been there - having to check if a variable is `null` or `undefined` before using it. This results in a lot of repetitive conditional checks that can clutter up our code.

With the introduction of the nullish coalescing operator in ECMAScript 2020, we have a cleaner way to handle `null` or `undefined` values.

In this post, I'll explain what the nullish coalescing operator is, demonstrate how to use it, and discuss why it's such an essential addition to the JavaScript language.

---

## What is the Nullish Coalescing Operator?

The *Nullish Coalescing Operator (??)* is a logical operator introduced in ECMAScript 2020 to handle default values for null or undefined.

> It returns the first operand if it’s not `null` or `undefined`. Otherwise, it returns the second operand.

The basic syntax looks like this:

```javascript
let name = value ?? 'Default';
```
If value is `null` or `undefined`, it will return 'Default'. If value has any other value such as '', 0, false, etc. it will return that value unchanged.

This allows us to assign default values more concisely without needing multiple conditional checks.

---

## Using the Nullish Coalescing Operator

Here are some common examples of how to use the nullish coalescing operator:

**Example 1: Basic Usage**

```javascript
let undefinedValue;
let defaultValue = 'default';
    
let result = undefinedValue ?? defaultValue;
console.log(result); // Outputs: 'default'
```

In this example, `undefinedValue` is `undefined`, so the Nullish Coalescing Operator returns `defaultVal`.

**Example 2: With Null Value**

```javascript
let nullValue = null;
let defaultValue = 'default';
    
let result = nullValue ?? defaultValue;
console.log(result); // Outputs: 'default'
```

In this case, `nullValue` is `null`, so again, the operator returns `defaultValue`.

**Example 3: With Non-Nullish Value**

```javascript
let nonNullishValue = 'I am defined';
let defaultValue = 'default';
    
let result = nonNullishValue ?? defaultValue;
console.log(result); // Outputs: 'I am defined'
```

In this case, `nonNullishValue` is neither `null` nor `undefined`, so the operator returns `nonNullishValue`.

**Example 4: With Zero and Empty String**

```javascript
let zeroValue = 0;
let defaultValue = 'default';
    
let result = zeroValue ?? defaultValue;
console.log(result); // Outputs: 0
    
let emptyStringValue = '';
result = emptyStringValue ?? defaultValue;
console.log(result); // Outputs: ''
```

In these cases, the operator returns `0` and `''` respectively, because it only checks for `null` or `undefined`, not other `"falsy"` values like `0`or `''`.

**Example 5: Object Property Assignment**

```javascript
let user = {
    firstName: null,
    lastName: 'Doe'
};
    
let firstName = user.firstName ?? 'John';
let lastName = user.lastName ?? 'Doe';
    
console.log(firstName); // Outputs: 'John'
console.log(lastName); // Outputs: 'Doe'
```

In this case, the `firstName` property is `null`, so the Nullish Coalescing Operator replaces it with `'John'`. The `lastName` property is `not null` or `undefined`, so it remains `'Doe'`.

**Example 6: Chaining**

The Nullish Coalescing Operator can be used for chaining operations, retrieving the first defined value in a list:

```javascript
let value1 = null;
let value2 = undefined;
let value3 = 'Hello, World!';
let value4 = 'Another Value';
    
let result = value1 ?? value2 ?? value3 ?? value4; // result will be 'Hello, World!'
```

In this case, `value1` and `value2` are `null` or `undefined`, so they are skipped. `value3` is the first non-nullish value, so it is returned.

**Example 7: Arrays**

```javascript
let arr = [null, undefined, 'Hello, World!'];
    
let value = arr[0] ?? 'Default Value'; // value will be 'Default Value'
value = arr[2] ?? 'Default Value'; // value will be 'Hello, World!'
```

In this case, the operator is used to check if a specific index in the array is `null` or `undefined`, and provide a default value if it is.

---

## Comparing || and ??

Both `||` (Logical OR) and `??` (Nullish Coalescing Operator) are used to provide default values for variables. However, there are subtle differences in how they operate, which can lead to different outcomes.

**=> Logical OR ||**

The Logical OR `||` operator returns the first operand if it is truthy. Otherwise, it returns the second operand. However, JavaScript considers the following values as falsy:

* false

* 0

* '' (empty string)

* NaN

* null

* undefined

This can lead to unexpected results when using `||` to provide default values. For example:

```javascript
let count = 0;
let displayCount = count || 'Not specified';
console.log(displayCount); // Output: 'Not specified'
```

In the above code, 0 is a valid value for a count, but since 0 is falsy, the `||` operator returns the second operand 'Not specified'.

**=> Nullish Coalescing Operator ??**

The Nullish Coalescing Operator `??` is a logical operator that returns its first operand if it's not null or undefined, otherwise it returns its second operand.

This makes `??` more suitable for providing default values, as it only falls back to the default if the original value is null or undefined, not for other falsy values like 0, false, or ''.

Using the previous example but with `??`:

```javascript
let count = 0;
let displayCount = count ?? 'Not specified';
console.log(displayCount); // Output: 0
```

In this case, `0` is correctly displayed, as the `??` operator correctly identifies that count is not null or undefined.

While both `||` and `??` can be used to provide default values, `??` is often a safer choice as it doesn't consider `0`, `false`, and `''` (empty string) as fallback conditions. This makes `??` especially useful in situations where these falsy values are valid and expected.

---

## Why It’s Essential for Clean Code

There are a few key reasons the nullish coalescing operator has become essential for writing clean JavaScript code:

 1. **Avoids Repetitive Conditionals** — As mentioned, it removes the need for multiple if/else checks throughout our code.

 2. **Default Parameter Values** — This makes it easy to define function parameter defaults in a clear way.

 3. **Optional Chaining** — Works great when chained with optional chaining for nested property access.

 4. **Readability** — Code using ?? is instantly understandable compared to deep conditional statements.

 5. **Future Proofing** — As JavaScript evolves, more features like this will continue improving the language. Adopting new syntax early makes our code ready for the future.

---

## Conclusion

The Nullish Coalescing Operator is an essential tool in JavaScript. It enhances code readability and avoids unexpected behaviors, making it a crucial part of any JavaScript developer’s toolkit.

## 🔥 Wait! 🔥

Give that like button some love! And if you’re feeling extra cheeky, hit follow too!
>  *Follow me on Instagram: [Click Here](https://www.instagram.com/codingwithjd/)*