Start Using Optional Chaining and Nullish Coalescing in React
Tags: coding, javascript, programming, react
Published: 2024-01-19 21:00:20

Since I started developing in React, I have noticed how most online snippets and tutorials avoid the optional chaining operator, as well as the nullish coalescing operator. Although they are fairly recent innovations, they are already over a year old.

So, I think the reason behind this is that there is a lack of education about what they are, how to start using them, how, why, and when. Let's try to address all of these points.

## What They Are

Let's see both the optional chaining operator and the nullish coalescing operator definition according to [MDN Web Docs](https://en.wikipedia.org/wiki/MDN_Web_Docs).

### [Optional Chaining](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining)

> _The optional chaining operator (**`?.`**) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid._
> 
> _The `?.` operator is like the `.` chaining operator, except that instead of causing an error if a reference is [nullish](https://developer.mozilla.org/en-US/docs/Glossary/Nullish) ([`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null) or [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined)), the expression short-circuits with a return value of `undefined`. When used with function calls, it returns `undefined` if the given function does not exist._ — [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining)

### [Nullish Coalescing](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator)

> _The **nullish coalescing operator (****`??`****)** is a logical operator that returns its right-hand side operand when its left-hand side operand is [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null) or [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined), and otherwise returns its left-hand side operand._ — [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining)

## How To Enable Them

Both operators were officially released with the [ECMA-262 11th Edition](https://262.ecma-international.org/11.0/) JavaScript language specification. Since these are quite fresh features, only certain versions of React support them.

In order to use them, the following requirements must be met:

- [Babel ≥ 7.8.0](https://babeljs.io/blog/2020/01/11/7.8.0)

- [Create React App ≥ 3.3.0](https://github.com/facebook/create-react-app/blob/main/CHANGELOG-3.x.md#330-2019-12-04)

Plus, TypeScript developers need [TypeScript ≥ 3.7](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html).

## How To Use Them

Let's see the syntax required to use both operators.

### Optional Chaining

```javascript
obj.val?.prop // default use
obj.val?.[expr] // optional chaining with expressions
obj.arr?.[index] // array item access with optional chaining
obj.func?.(args) // optional chaining with function calls
```

### Nullish Coalescing

```javascript
leftExpr ?? rightExpr // default use
```

## Why and When To Use Them

Let's see why these two operators were introduced to JavaScript and when you should use them to take advantage of their power.

### Optional Chaining

When developing in JavaScript, you often need to access deeply-nested properties from tree-like structures. The common solution is to write a long chain of property accesses. The problem is that if any of the intermediate references in the chain is `null` or `undefined`, JavaScript will throw a `_TypeError: Cannot read property ‘name' of undefined_` error.

So, you may end up writing custom logic to avoid this from happening. Not only is this code ugly, but it also makes your codebase less readable. This is why the optional chaining operator was introduced.

Before optional chaining, you had to write something like this:

```javascript
if (obj && object.property1 && object.property1.property2) {
    object.property1.property2.toLowerCase()
} 
```

With optional chaining, you can achieve the same result with a single, cleaner, and more readable line of code:

```javascript
obj.property1?.property2.toLowerCase()
```

This was just a simple example, but you can find a more in-depth guide [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining#examples).

Plus, keep in mind that the optional chaining operator works only for declared variables. If there was no `obj` variable, then a `ReferenceError` error would be thrown.

Also, you should use `?.` only with optional properties and variables. This means that if according to your coding logic the `obj` variable must exist, but the `property1` property is optional, you should write `obj.property1?.property2`.

### Nullish Coalescing

When you need a variable to have a default value, you may think of using the OR operator ([`||`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR)), as follows:

```javascript
let value;
let defaultValue = value || 'Hello World!';
```

This may turn into an error very difficult to spot. In fact, `||` is a boolean logical operator. So, the left-hand-side operand is automatically converted to a boolean during evaluation time. This means that in case the left-hand-side operand is any JavaScript _falsy_ value (`0`, `''`, `NaN`, `null`, `undefined`), the default value will not be returned.

The nullish coalescing operator was introduced to overcome this issue. In fact, it avoids this pitfall by only returning the second operand when the first one evaluates to either `null` or `undefined` (but no other _falsy_ values):

```javascript
const nullValue = null;
const emptyText = ""; // falsy
const aNumber = 42;

const val1 = nullValue ?? "Default Value 1";
const val2 = emptyText ?? "Default Value 2";
const val3 = aNumber ?? 0;

console.log(val1); // "Default Value 1"
console.log(val2); // "" (as the empty string is not null or undefined)
console.log(val3); // 42
```

This was just a simple example, but you can find a more in-depth guide [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator#examples).

## Conclusion

Today we looked at what the optional chaining and nullish coalescing operators are, how to use them, why, and where. Although they were introduced in JavaScript over a year ago, many developers still have not tried them. This is because they are still quite a novelty and education is necessary to understand everything required to start adopting them, and this what was this article was aimed at.

Thanks for reading! I hope that you found this article helpful.
  
***
_The post "[Start Using Optional Chaining and Nullish Coalescing in React](https://writech.run/blog/start-using-optional-chaining-and-nullish-coalescing-in-react-322bdf24b78c/)" appeared first on [Writech](https://writech.run)._