Optional Chaining and Nullish Coalescing: Safe Property Access in JavaScript
Tags: javascript, webdev, es6, coding
Published: 2023-09-09 18:41:13

Ever seen the `Cannot read property ‘x’ of undefined` error in your JavaScript? If so, you’re not alone. Many of us get this error when working with JavaScript objects and properties.

But guess what? There are features like Optional Chaining and Nullish Coalescing that can help. In this article, we’ll see how these features keep our code safe and clean.

## Why does property access need to be safer?

Well, no one likes errors. And that `Cannot read property ‘x’ of undefined` error? We’ve all seen it. It pops up when we try to use a property or method that’s not there. Old ways to avoid this error made our code look messy.

For example:

```javascript
let user = {};
let username = user && user.details && user.details.name;
```

Looks a bit cluttered, right? But there’s a cleaner way.

## Optional Chaining

Here’s what Optional Chaining does: it helps us reach values in objects even if something might be missing.

```javascript
let username = user?.details?.name;
```

## When should you use Optional Chaining?

* To safely check nested properties.
    
* To call functions without risk.
    
* To safely check items in arrays.
    

But, be careful. Don’t overuse it, or you might miss other errors.

## Nullish Coalescing

Here’s a quick quiz. What does the Nullish Coalescing operator (`??`) do? It checks the left value. If it’s `null` or `undefined`, it goes with the right value. If not, it sticks with the left.

```javascript
let x = value ?? "default";
```

Also, a quick tip about the `||` operator. It can be tricky, with values like `0` or an `empty string`. In JavaScript, values like `0`, `“”`, `NaN`, `false`, `null`, and `undefined` are `falsy`. The fun part? Nullish Coalescing only looks at `null` and `undefined`.

{% twitter https://twitter.com/mainulspace/status/1700191434261864870?s=20 %} 

## Usage Scenarios for Nullish Coalescing

* Setting default values for variables.
    
* Handling configurations with potential `null/undefined` values.
    
* More explicit intention than the `||` operator.
    
* Avoids unexpected behaviors with other `falsy` values like `0` or `“”`.
    

## Combining Optional Chaining with Nullish Coalescing

Want to mix Optional Chaining and Nullish Coalescing? It’s like magic.

```javascript
let setting = user?.preferences?.themeColor ?? "blue";
```

If the user or preferences are `undefined` or `null`, or if `themeColor` is not set, it will assign the setting the default value of “blue”.

## Performance Considerations

While these features enhance code readability and safety, you might think about speed. Do they slow down the performance of the app? For most cases, using Optional Chaining or Nullish Coalescing won’t slow you down.

But if you use them often, especially in large-scale applications or loops that run often, you might see some delay. If you’re unsure, always check your app’s performance.

## **Browser and Environment Support**

Are you thinking of using these features? First, check if your browsers support them. As of 2020, most new browsers do. But some old ones might not. Tools like Babel can help. Or check [Can I use](https://caniuse.com/).

## Conclusion

Think about your projects. How much can these features help? These are great features for JavaScript developers. They make code neat, make intentions clearer, and reduce potential errors. And that means robust apps.

If you found this article useful or have more insights on the topic, feel free to connect with me on [**Twitter**](https://twitter.com/mainulspace) and [**LinkedIn**](https://www.linkedin.com/in/mainulspace/). Let’s continue the conversation there!

## Read Next...
{% embed https://dev.to/mainulspace/10-lesser-known-javascript-array-methods-you-mightve-missed-32b3 %}

{% embed https://dev.to/mainulspace/short-circuit-evaluation-making-your-code-more-concise-2jne %} 

{% embed https://dev.to/mainulspace/javascript-tricky-interview-questions-2023-14li %}