😲🤯The most outstanding new feature in Javascript you need to know about: Optional Chaining
Tags: javascript, webdev, beginners, tutorial
Published: 2019-09-15 11:05:23

Optional chaining is a game-changer for everybody how is working with Javascript. It is as essential as Fat Arrow Functions or 'let' and 'const'. Let's discuss what problems it solves, how it works, and how it will make your life easier.


### The problem

Imagine the following:
You are working on that piece of code that loads data from an API. The object you are getting back is deeply nested, which means you need to go down a long path of object properties.

```javascript
// API response object
const person = {
    details: {
        name: {
            firstName: "Michael",
            lastName: "Lampe",
        }
    },
    jobs: [
        "Senior Full Stack Web Developer",
        "Freelancer"
    ]
}
// Getting the firstName
const personFirstName = person.details.name.firstName;
```

Not this would be bad practice to leave the code like this right now. A better solution could like this:

```javascript
// Checking if firstName exists
if( person &&
    person.details &&
    person.details.name ) {
        const personFirstName = person.details.name.firstName || 'stranger';
}
```
As you see in the example even something simple like getting the firstName of a person can be hard to get right.
So this is why we had frameworks like `lodash` to deal with things like this.

```javascript
_.get(person, 'details.name.firstName', 'stranger');
```
'loadash' makes the code more readable, but now you have introduced a big dependency into your codebase. You need to update it, and if you ware working on a team, you have to spread the knowledge and use of it to the team. So this is also not the ideal solution. 

### The Solution

Optional chaining has a solution for all of that (besides the team knowledge problem).

#### How does it work

Optional chaining introduces new syntax that at first will look strange to you, but after just a few minutes you will get used to it. 

```javascript
const personFirstName = person?.details?.name?.firstName;
```
Okay, so you probably now have a lot of question marks above your head (pun intended).  So the new thing here is the `?`. Here is how you have to think about it. If there is a `?.` at the beginning of a property, it is as you would ask your self does person exists? Or in a more javascript way, has `person` the value `null` or `undefined`? If yes then I will not return an error but just `undefined`. So `personFirstName` will have the value of `undefined`. This question will repeat for `details?` and `name?`. If any of these values is 'null' or `undefined`, then `personFirstName` will also be `undefined`. This is called `Short-circuiting`. Once javascript finds a `null` or `undefined`  it will short circuit and stop going deeper.

#### Default values

We also need to learn about the `Nullish coalescing operator`. Okay, this sounds hard to learn. But actually, it is not. Let's look at the following example:

```javascript
const personFirstName = person?.details?.name?.firstName ?? 'stranger';
```
The `Nullish coalescing operator` is represented as `??`. It is also pretty easy to read. If the left side is `undefined` than `personFirstName` will get the value of the right side from `??`. That's it pretty easy.

#### Dynamic properties

Sometimes you want to access a dynamic value. It could be an array value or just a dynamic property of an object.

```javascript
const jobNumber = 1;
const secondJob = person?.jobs?.[jobNumber] ?? 'none';
```
The important thing here to understand is that `jobs?.[jobNumber]` is the same as `jobs[jobNumber]` but it will not throw an error; instead, it will return 'none'.

####  Function or method call

Sometimes you will work on objects where you don't know if they have a method or not. Here we can use the `?.()` syntax or with arguments `?.({ some: 'args'})` . It works as you would think it works. If this method does not exist on that object, it will return `undefined`.

```javascript
const currentJob = person?.jobs.getCurrentJob?.() ?? 'none';
```
If there is no `getCurrentJob` function than `currentJob` will be `none`. 

#### Start using it today

Right now no browser supports this out of the box — Babel to the rescue. There is a `babel.js` plugin already that is pretty easy to integrate if you have already Babel setup.

[babel-plugin-proposal-optional-chaining](https://babeljs.io/docs/en/babel-plugin-proposal-optional-chaining)

#### Finale words
I think this will make a lot of Javascript code easier to read and also less error-prone. If you want, you can also read the [proposal](https://github.com/tc39/proposal-optional-chaining). I hope that this post made you a little bit smarter, and you now want to integrate Optional Chaining into your workflow!

It would help me if you could do the following for me.
Go to [Twitch](https://twitch.tv/lampewebdev) and leave a follow for me! If just a few people would do that, then this would mean the world to me! ❤❤❤😊

**👋Say Hallo!** [Instagram](https://www.instagram.com/lampewebdev/) | [Twitter](https://twitter.com/lampewebdev) | [LinkedIn](https://www.linkedin.com/in/michael-lazarski-25725a87) | [Medium](https://medium.com/@lampewebdevelopment) | [Twitch](https://dev.to/twitch_live_streams/lampewebdev) | [YouTube](https://www.youtube.com/channel/UCYCe4Cnracnq91J0CgoyKAQ)