[update] I've removed the optional chaining syntax plugin as it is required by the transform anyway.
Do Expressions solve a case when you want to declare a
variable and assign it a value with a more complex
expression than a single ternary. Consider the following
render method which renders a color component based on
There are two deficencies in this code. One is that we have
let instead of
signals that it could be modified anywhere in the rest of
the code before we render
The second deficiency is related to the first, in that the if statements aren't grouped except by convention. We could easily put the if statements anywhere in the render function (perhaps after a large block of other complicated code) which makes it harder to debug.
The do expression version solves these issues. We get to
const for component, indicating that the value
won't change later, and we also get to group the logic for
component value. This makes debugging the
component easier later when we're searching for
all of the places it could be modified.
Expanding on the previous example, let's say we're using
GraphQL to fetch our data which is one case where deep
object access can occur. The GraphQL response is passed in
data, but attempting to destructure further is risky if
there are nullable values in the chain.
We can clean this up into something very similar to normal prop access:
Note that you can't destructure on
undefined so the
following can throw:
You'll need a babel config like this to run the above
examples, and a babel version of >= 7 which you can
currently install as
Also note that these plugins will be in stage-0, but it's still good practice to list them out if you're using them.