13-ES6++: Optional Chaining in Javascript
Tags: javascript, es6, esnext
Published: 2022-11-26 04:32:51

---
title: 13-ES6++: Optional Chaining in Javascript
published: true
description: 
series: es6++
tags: javascript, es6, esnext
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r1du09mkaw5lxzm97hzf.png
# Use a ratio of 100:42 for best results.
# published_at: 2022-10-25 09:51 +0000
---

## Optional Chaining

Optional chaining is a new feature that was released in ES2020 (`ES11`). It is a new way to access properties of objects without having to check if the object is undefined or not. It is a very useful feature that can be used to avoid writing long if statements.

## In simple words?

Optional chaining is a new way to access properties of objects without having to check if the object is undefined or not. It is a very useful feature that can be used to avoid writing long if statements.

## How to use it?

The syntax for optional chaining is `?.`. It is used to access properties of objects. It is used to avoid writing long if statements.

Let's see the old way first

```js
const user = {
  name: "Hasan",
  age: 20,
  address: {
    city: "Cairo",
  },
};

if (user && user.address && user.address.city) {
  console.log(user.address.city);
}
```

Now let's see the new way

```js
const user = {
  name: "Hasan",
  age: 20,
  address: {
    city: "Cairo",
  },
};

if (user?.address?.city) {
  console.log(user.address.city);
}
```

See? It is much shorter and easier to read.

So basically you don't have to check if the object is undefined or not. You can just use `?.` to access properties of objects and its nested objects.

## What if the object is undefined?

When using optional chaining, if the object is undefined, it will return undefined. So you don't have to check if the object is undefined or not.

```js
const user = undefined;

console.log(user?.name); // undefined because user is undefined
```

## What if the property doesn't exist?

Same exact situation as above. If the property doesn't exist, it will return undefined.

```js
const user = {};

console.log(user?.name); // undefined because user.name doesn't exist
```

## What if the property is null?

If the property is null, it will return null.

```js
const user = {
  name: null,
};

console.log(user?.name); // null because user.name is null
```

## What if the property is 0?

If the property is 0, it will return 0.

```js
const user = {
  age: 0,
};

console.log(user?.age); // 0 because user.age is 0
```

## What if the property is an empty string?

If the property is an empty string, it will return an empty string.

```js
const user = {
  name: "",
};

console.log(user?.name); // "" because user.name is an empty string
```

Of course if you're sure that the object is defined you won't need to use the optional chaining feature. But if you're not sure, it is a very useful feature to use.

## Is it possible to check with array indexes?

Yes, it is possible to check with array indexes. But you have to use brackets instead of dot notation.

```js
const user = {};

console.log(user.friends?.[0]); // undefined because user.friends[0] doesn't exist
```

We can go over with more complex nested objects and arrays, for example i want to access the name of the first index in the friends array of the user object.

```js
const user = {
  friends: [
    {
      name: "Ahmed",
    },
  ],
};

console.log(user.friends?.[0]?.name); // Ahmed
```

Here we defined the `?.` before the array brackets and the dot notation.

## Nesting functions

It is possible to use optional chaining with functions. For example, i want to call the `getName` function of the user object and that function returns an object that contains `first` and `last` properties.

```js
const user = {
  getName: () => {
    return {
      first: "Hasan",
      last: "Zohdy",
    };
  },
};

console.log(user.getName?.()?.first); //Hasan
console.log(user.getName?.()?.middle); //undefined
```

You see, we added it just before the function parentheses, then we can continue our chain with dot notation.

## 💡 A Pro tip

Don't overuse optional chaining, if you're certain about an object that already exists, so don't use it with it, but if you're not sure with it or with its nested objects, then you can use it.

```ts
const user = {};

// ❌
console.log(user?.name); // undefined

// ✅
console.log(user.name); // undefined
```

Because we already knows that the user object is defined, so we don't need to use optional chaining with it.

```ts
const user = {};

// ❌
console.log(user?.address?.city); // undefined

// ✅
console.log(user.address?.city); // undefined
```

I know that the `user` already exists, but `address` may or may not exist, thus we need to use optional chaining with the address only and not with the user.

## Should i use it in my code? 🤔

Of course you should, it will relieve you from writing long if statements and it will make your code much cleaner and easier to read.

## A tip about feature usage

If your project uses a bundler like [webpack](https://webpack.js.org/) or [rollup](https://rollupjs.org/guide/en/), then you can use the `optional chaining operator` in your code. But if you are using a browser, then you should use a transpiler like [babel](https://babeljs.io/) to transpile your code to ES5. You can use [babel repl](https://babeljs.io/repl) to transpile your code.

## 🎨 Conclusion

Optional chaining is a new feature that was released in ES2020 (`es9`). It is a new way to access properties of objects without having to check if the object is undefined or not. It is a very useful feature that can be used to avoid writing long if statements and checks.

## ☕♨️ Buy me a Coffee ♨️☕

If you enjoy my articles and see it useful to you, you may [buy me a coffee](https://www.paypal.com/paypalme/hassanzohdy), it will help me to keep going and keep creating more content.

## 😍 Join our community

Join our community on [Discord](https://discord.gg/pb2vmdfhGf) to get help and support (Node Js 2023 Channel).

## 📚 Bonus Content 📚

You may have a look at these articles, it will definitely boost your knowledge and productivity.

General Topics

* [Event Driven Architecture: A Practical Guide in Javascript](https://dev.to/hassanzohdy/event-driven-architecture-the-best-paradigm-that-i-love-to-work-with-in-javascript-and-node-js-1gnk)
* [Best Practices For Case Styles: Camel, Pascal, Snake, and Kebab Case In Node And Javascript](https://dev.to/hassanzohdy/best-practices-for-case-styles-camel-pascal-snake-and-kebab-case-in-node-and-javascript-55oi)
* [After 6 years of practicing MongoDB, Here are my thoughts on MongoDB vs MySQL
](https://dev.to/hassanzohdy/after-6-years-of-practicing-mongodb-here-are-my-thoughts-on-mongodb-vs-mysql-574b)

Packages & Libraries

* [Collections: Your ultimate Javascript Arrays Manager](https://dev.to/hassanzohdy/collections-your-ultimate-javascript-array-handler-3o15)
* [Supportive Is: an elegant utility to check types of values in JavaScript](https://dev.to/hassanzohdy/supportive-is-an-elegant-utility-to-check-types-of-values-in-javascript-1b3e)
* [Localization: An agnostic i18n package to manage localization in your project](https://dev.to/hassanzohdy/mongez-localization-the-simplest-way-to-translate-your-website-regardless-your-favorite-framework-4gi3)

 React Js Packages

* [useFetcher: easiest way to fetch data in React Js](https://dev.to/hassanzohdy/usefetcher-the-easiest-way-to-fetch-data-in-react-45o9)

Courses (Articles)

* [Node Js 2023 Course: Node With Typescript, The Ultimate Guide](https://dev.to/hassanzohdy/nodejs-course-2023-introduction-to-nodejs-3n4e)
* [React Js: Let"s Create File Manager With React Js and Node Js](https://dev.to/hassanzohdy/lets-create-a-file-manager-from-scratch-with-react-and-typescript-chapter-i-a-good-way-to-expand-your-experience-5g4k)