Optional Chaining (?.)

jasmine
2 min readAug 26, 2022

--

const value = obj?.propOne?.propTwo?.propThree?.lastProp;

In the code snippet above, we are checking if obj is null or undefined, then propOne, then propTwo, and so on.

Optional Chaining + Nullish Coalescing

const data = obj?.prop ?? "fallback string";

If the item to the left of ?? is nullish, the item to the right will be returned.

Let’s see how optional chaining makes your code simpler when accessing potentially null or undefined properties.

let name = movie.director?.name;

is equivalent to:

let name;if (movie.director != null) {name = movie.director.name;}

?. simplifies getDirector() function by reducing 2 lines of code. That's why I like optional chaining.

But the optional chaining feature can do more than that. You are free to use multiple optional chaining operators in the same expression. You can even use it to access array items safely!

function getLeadingActor(movie) {if (movie.actors && movie.actors.length > 0) {return movie.actors[0].name;}}getLeadingActor(movieSmall); // => undefinedgetLeadingActor(movieFull);  // => 'Harrison Ford'

With the use of optional chaining, this task is trivial to solve:

function getLeadingActor(movie) {return movie.actors?.[0]?.name;}getLeadingActor(movieSmall); // => undefinedgetLeadingActor(movieFull);  // => 'Harrison Ford'

actors?. makes sure actors property exists. [0]?. makes sure that the first actor exists in the list.

The 3 forms of optional chaining

The first form object?.property is used to access a static property:

const object = null;object?.property; // => undefined

The second form object?.[expression] is used to access a dynamic property or an array item:

const object = null;const name = 'property';object?.[name]; // => undefinedconst array = null;array?.[0]; // => undefined

Finally, the third form object?.([arg1, [arg2, ...]]) executes an object method:

const object = null;object?.method('Some value'); // => undefined

--

--