The Optional Chaining operator

I was all smiles today šŸ˜„. Why? I naturally used some piece of code I had read about recently and it felt good. What was it? Optional chaining! I know I’m late to the party šŸ˜, but let’s get into it

In simple words, optional chaining prevents you from doing this:

resonse.data && response.data.animals && response.data.animals.cats && response.data.animals.cats.map(cat => {

// blah blah
})

Do you see the ugliness in that? Yeah, guaranteed it’s a bit exaggerated but you get the point.

Let’s talk a look at how we can clean this up. First, let’s have a look at a snippet of the response we are dealing with.

data: {
    animals {
        cats [
            {
                id: 0001,
                name: "Fuzzy",
                breed: "Bengal",
                weight: 10,
                age: 1,
            }.
            {
                id: 0002,
                name: "Tiger",
                breed: "Abyssinian",
                weight: 30,
                age: 3,
            },
            {
               ....
            }

        ],
        dogs [
            {
              ...
            }
        ],

    }
}

Optional Chaining

Thankfully, we now have an optional chaining operator, ?. to the rescue! It has been promoted to Stage 4 by TC39. With optional chaining, all we have to do is:

response?.data?.animals?.cats.map(cat => {

// blah blah

})

Pretty simple. No need to check to see if the nested properties exist before using them. Just use them - Well, you may need to pass it through babel. Read more about optional chaining and it’s browser compatibility here

PS: You should not be dealing with such responses in 2020. Explore GraphQL to see how it can help get the right responses you need.