Optional Chaining in React Native

July 2, 2018 • ☕️ 1 min read

JavascriptReact NativeESNextWeb Dev

asset 1

In June 2018 release of React Native (0.56.0) they had announced the enabling of optional chaining operator ?. plugins. Previously we’ve to manually add babel-plugin for syntax-optional-chaining to use this operator. So, here comes the question; what is the purpose of this optional chaining operator thing?

Problems in Property Chaining

We normally encounters the state where an expected member of a property chain is undefined or null. Suppose we’re getting the data from an API call; we expect user.profile.lastName to exist but for some reason the lastName is missing from the user object.

asset 2

Let’s see some of the existing solutions that we can use to solve this issue -


asset 3

Ternary Operator

asset 4

Logic Expression

asset 5

In my opinion, this procedures are bit of Ugly, Noisy, Burdensome and Verbose. Here’s where optional chaining comes in action. We can have the fun of using it like this:

asset 6

That’s much easier, right? As we’ve seen the usefulness of this feature, we can go ahead and take a deep dive.

Array index Out of Bound is a common phenomena in programming world, optional chaining works for array property access too:

asset 7

We can also check the existence of a function:

asset 8

Expressions will not execute farther if that chain is not complete. Under the hood, the expressions is practically transformed to this:

asset 9

Basically in a short we can sum up this like — nothing after the optional chain operator ? will be executed if the value is undefined or null. So, in a whole optional chaining reduces the need for if statements, imported libraries like lodash, and the need for chaining with && logical operator.


Here’s one of the links of the proposal of adding optional chaining in Javascript, and this is the babel-plugin-proposal link. Finally the commit link of adding optional-chaining plugin to RN 0.56

Written by Nayeem Reza
Software Engineer | Tech Enthusiast | Traveler