Optional Chaining in React Native
July 2, 2018 • ☕️ 1 min read
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.
Let’s see some of the existing solutions that we can use to solve this issue -
Try-Catch
Ternary Operator
Logic Expression
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:
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:
We can also check the existence of a function:
Expressions will not execute farther if that chain is not complete. Under the hood, the expressions is practically transformed to this:
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.
Reference
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