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


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

    you write shorter and more concise JavaScript
  2. Who Am I? Mohamed Oun Front-end engineer at Prodigy AI

    @Mohamed3on Mohamed3on@gmail.com Mohamed3on.online
  3. Optional what now?

  4. JavaScript has a problem..

  5. 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
  6. Current solutions

  7. Current solutions • Use nested ternaries • Opinion: Please don’t

  8. Current solutions • Check if the properties exist before accessing

    them • Opinion: Clunky, not optimal
  9. Current solutions • Use an external library • Opinion: Nice!

    But wouldn’t it be better if it was built into the language?
  10. Enter: The optional chaining operator!

  11. 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
  12. 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
  13. Inspirations

  14. This operator already exists with similar semantics in: • C#:

    Null-conditional operator • Swift: Optional Chaining • CoffeeScript: Existential operator
  15. 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
  16. That’s it! Thank you