Slide 1

Slide 1 text

Optional Chaining Operator in JavaScript A new proposal to help you write shorter and more concise JavaScript

Slide 2

Slide 2 text

Who Am I? Mohamed Oun Front-end engineer at Prodigy AI @Mohamed3on [email protected] Mohamed3on.online

Slide 3

Slide 3 text

Optional what now?

Slide 4

Slide 4 text

JavaScript has a problem..

Slide 5

Slide 5 text

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

Slide 6

Slide 6 text

Current solutions

Slide 7

Slide 7 text

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

Slide 8

Slide 8 text

Current solutions • Check if the properties exist before accessing them • Opinion: Clunky, not optimal

Slide 9

Slide 9 text

Current solutions • Use an external library • Opinion: Nice! But wouldn’t it be better if it was built into the language?

Slide 10

Slide 10 text

Enter: The optional chaining operator!

Slide 11

Slide 11 text

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

Slide 12

Slide 12 text

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

Slide 13

Slide 13 text

Inspirations

Slide 14

Slide 14 text

This operator already exists with similar semantics in: • C#: Null-conditional operator • Swift: Optional Chaining • CoffeeScript: Existential operator

Slide 15

Slide 15 text

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

Slide 16

Slide 16 text

That’s it! Thank you