Upgrade to Pro — share decks privately, control downloads, hide ads and more …

The optional chaining operator

The optional chaining operator

A lightning talk about the new JS proposal for an optional chaining operator. Given at the React Open Source meetup in Berlin.

Mohamed Oun

May 09, 2018

More Decks by Mohamed Oun

Other Decks in Programming


  1. Optional Chaining Operator in JavaScript A new proposal to help

    you write shorter and more concise JavaScript
  2. Let’s say you want to access a nested property •

    We have users, some of them have addresses, some don’t • We want to access the street number of a user’s address
  3. Current solutions • Use an external library • Opinion: Nice!

    But wouldn’t it be better if it was built into the language?
  4. Optional Chaining Operator • A proposal for an operator to

    solve this problem in an simpler way as part of the language • Shorter, clearer than all the current solutions • No need for an external library • No more ’Cannot read property X of undefined’ errors
  5. How it works • Use the operator ?. • checks

    if the Left-Hand-Side of it is not null or undefined • If it is, the expression short-circuits (returns undefined), else the Right-Hand-Side is evaluated • Works on properties, arrays and functions
  6. This operator already exists with similar semantics in: • C#:

    Null-conditional operator • Swift: Optional Chaining • CoffeeScript: Existential operator
  7. Status of the proposal • At Stage 1 (Proposal, experimental),

    close to being Stage 2 (Formal draft) • Can already be used with Babel (But use with caution) • Supported by Flow