JavaScript Optional Chaining ?.
It scratches a huge itch
React encourages you to write declarative code. Every now and then you end up writing code that looks like this:
payload && payload.data && payload.data.items && payload.data.items[0] && ( /*.. whatever .. */ )
It is a bummer to even write smaller expressions such as
onClose && onClose();
Now for CRA based apps, you can use the new optional chaining feature. First, you must upgrade to version 3.3.0. If applicable, you may also need to upgrade your TypeScript to 3.7+ and probably upgrade VSCode,
Here are the use cases.
a?.b // a == null ? undefined : a.b
a?.[x] // a == null ? undefined : a[x]
a?.b() // a == null ? undefined : a.b()
a?.() // a == null ? undefined : a()
Stacking
You can stack the optional chaining operator. The initial examples in this article now become:
payload?.data?.items?.[0] && ( /*.. whatever .. */ )
onClose?.()
// if onClose is not a function, an error is thrown
The more code there is the more chances of human errors. Declarative style with functional programming patterns and constructs like ‘optional chaining’ help write code that is concise and less error prone.