惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Cisco Talos Blog
Cisco Talos Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
爱范儿
爱范儿
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Jina AI
Jina AI
雷峰网
雷峰网
The Register - Security
The Register - Security
The Cloudflare Blog
博客园 - 【当耐特】
M
MIT News - Artificial intelligence
I
InfoQ
博客园 - 三生石上(FineUI控件)
H
Help Net Security
博客园 - 司徒正美
Vercel News
Vercel News
WordPress大学
WordPress大学
S
SegmentFault 最新的问题
云风的 BLOG
云风的 BLOG
B
Blog
Google DeepMind News
Google DeepMind News
B
Blog RSS Feed
L
LangChain Blog
人人都是产品经理
人人都是产品经理
GbyAI
GbyAI
T
The Blog of Author Tim Ferriss
T
Tailwind CSS Blog
aimingoo的专栏
aimingoo的专栏
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Recorded Future
Recorded Future
小众软件
小众软件
Martin Fowler
Martin Fowler
罗磊的独立博客
Stack Overflow Blog
Stack Overflow Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
酷 壳 – CoolShell
酷 壳 – CoolShell
腾讯CDC
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Apple Machine Learning Research
Apple Machine Learning Research
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - Franky
Hugging Face - Blog
Hugging Face - Blog
Y
Y Combinator Blog
V
Visual Studio Blog
F
Fortinet All Blogs
Microsoft Azure Blog
Microsoft Azure Blog
大猫的无限游戏
大猫的无限游戏
Engineering at Meta
Engineering at Meta
N
Netflix TechBlog - Medium
V
V2EX
Blog — PlanetScale
Blog — PlanetScale

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback()
How to Use JavaScript Optional Chaining
Dmitri Pavlutin · 2019-08-21 · via Dmitri Pavlutin Blog

There are JavaScript features that vastly change the way you code. Starting from ES2015 and beyond, the features that influenced the most my code are destructuring, arrow functions, classes, and modules system.

Optional chaining, as a part of ES2020, changes the way properties are accessed from deep objects structures. Optional chaining is also available in TypeScript, starting from version 3.7.

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

1. The problem

Due to the dynamic nature of JavaScript, an object can have a very different nested structure of objects.

Usually, you deal with such objects when:

  • Fetching remote JSON data
  • Using configuration objects
  • Having optional properties

While this gives flexibility for an object to support different shapes of data, it comes with the price of increased complexity when accessing the properties of such objects.

bigObject can have different set of properties during runtime:


// One version of bigObject

const bigObject = {

// ...

prop1: {

//...

prop2: {

// ...

value: 'Some value'

}

}

};

// Other version of bigObject

const bigObject = {

// ...

prop1: {

// Nothing here

}

};


Thus you have to manually check the properties existence:


// Later

if (bigObject &&

bigObject.prop1 != null &&

bigObject.prop1.prop2 != null) {

let result = bigObject.prop1.prop2.value;

}


That's a lot of boilerplate code. It would be great to avoid writing it.

Let's see how optional chaining solves this problem, reducing boilerplate conditionals.

2. Easy deep access of properties

Let's design an object that holds movie information. The object contains a title required property, and optional director and actors.

movieSmall object contains only the title, while movieFull contains the full set of properties:


const movieSmall = {

title: 'Heat'

};

const movieFull = {

title: 'Blade Runner',

director: { name: 'Ridley Scott' },

actors: [{ name: 'Harrison Ford' }, { name: 'Rutger Hauer' }]

};


Let's write a function that gets the director's name. Remember that the director property might be missing:


function getDirector(movie) {

if (movie.director != null) {

return movie.director.name;

}

}

getDirector(movieSmall); // => undefined

getDirector(movieFull); // => 'Ridley Scott'


if (movie.director) {...} condition is used to verify whether the director property is defined. Without this precaution, in case of accessing movieSmall object's director, JavaScript would throw an error TypeError: Cannot read property 'name' of undefined.

This is the right place to use the new optional chaining feature, and remove the movie.director existence verification. The new version of getDirector() looks much shorter:


function getDirector(movie) {

return movie.director?.name;

}

getDirector(movieSmall); // => undefined

getDirector(movieFull); // => 'Ridley Scott'


Inside the expression movie.director?.name you can find ?.: the optional chaining operator.

In the case of movieSmall, the property director is missing. As a result, movie.director?.name evaluates to undefined. The optional chaining operator prevents throwing TypeError: Cannot read property 'name' of undefined.

Contrary, in the case of movieFull, the property director is available. movie.director?.name evaluates normally to 'Ridley Scott'.

In simple words, the code snippet:


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.

2.1 Array items

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!

The next task is to write a function that returns the leading actor name of a movie.

Inside the movie object, the actors array can be empty or even missing, so you have to add additional conditionals:


function getLeadingActor(movie) {

if (movie.actors && movie.actors.length > 0) {

return movie.actors[0].name;

}

}

getLeadingActor(movieSmall); // => undefined

getLeadingActor(movieFull); // => 'Harrison Ford'


if (movie.actors && movies.actors.length > 0) {...} conditional is required to be sure that movie contains the actors property, and this property has at least one actor.

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


function getLeadingActor(movie) {

return movie.actors?.[0]?.name;

}

getLeadingActor(movieSmall); // => undefined

getLeadingActor(movieFull); // => 'Harrison Ford'


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

3. Default with nullish coalescing

A new proposal named nullish coalescing operator ?? handles undefined or null, defaulting them to a specific value.

The expression variable ?? defaultValue results to defaultValue if the variable is undefined or null. Othewise the expression evaluates to variable value.


const noValue = undefined;

const value = 'Hello';

noValue ?? 'Nothing'; // => 'Nothing'

value ?? 'Nothing'; // => 'Hello'


Nullish coalescing can improve the optional chaining by defaulting to a value when the chain evaluates to undefined.

For example, let's change getLeading() function to return "Unknown actor" when there are no actors in the movie object:


function getLeadingActor(movie) {

return movie.actors?.[0]?.name ?? 'Unknown actor';

}

getLeadingActor(movieSmall); // => 'Unknown actor'

getLeadingActor(movieFull); // => 'Harrison Ford'


4. The 3 forms of optional chaining

You can use optional chaining in the following 3 forms.

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]; // => undefined



const array = null;

array?.[0]; // => undefined


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


const object = null;

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


These forms can be combined to create a long optional chain, if you need it:


const value = object.maybeUndefinedProp?.maybeNull()?.[propName];


5. Short-circuiting: stopping on null/undefined

What's interesting about the optional chaining operator is that as soon as a nullish value is encountered on its left-hand side leftHandSide?.rightHandSide, the evaluation of the right-hand side accessors stops. This is called short-circuiting.

Let's look at an example:


const nothing = null;

let index = 0;

nothing?.[index++]; // => undefined

index; // => 0


nothing holds a nullish value, so the optional chaining evaluates to undefined right away, and skips the evaluation of the accessors on the right side. Because of that index number is not incremented.

6. When to use optional chaining

Resist the urge to use optional chaining operator to access any kind of property: that would lead to a misguided usage. The next section explains when to use it correctly.

6.1 Access properties of potentially nullish

?. must be used only near the properties that can potentially be nullish: maybeNullish?.prop. In other cases, use the good-old property accessors: .property or [propExpression].

Recall the movie object. Looking at the expression movie.director?.name, because director can be undefined, it's correct to use the optional chaining operator near director property.

Contrary, it doesn't make sense to use ?. to access the movie title: movie?.title. The movie object is not going to be nullish.


// Good

function logMovie(movie) {

console.log(movie.director?.name);

console.log(movie.title);

}

// Bad

function logMovie(movie) {

// director needs optional chaining

console.log(movie.director.name);

// movie doesn't need optional chaining

console.log(movie?.title);

}


6.2 Often there are better alternatives

The following function hasPadding() accepts a style object with an optional padding property. The padding has optional properties left, top, right, bottom.

Let's try to use the optional chaining operator:


function hasPadding({ padding }) {

const top = padding?.top ?? 0;

const right = padding?.right ?? 0;

const bottom = padding?.bottom ?? 0;

const left = padding?.left ?? 0;

return left + top + right + bottom !== 0;

}

hasPadding({ color: 'black' }); // => false

hasPadding({ padding: { left: 0 } }); // => false

hasPadding({ padding: { right: 10 }}); // => true


While the function correctly determines if the element has padding, it's overwhelming to use the optional chaining for every property.

A better approach is to use the object spread operator to default the padding object to zero values:


function hasPadding({ padding }) {

const p = {

top: 0,

right: 0,

bottom: 0,

left: 0,

...padding

};

return p.top + p.left + p.right + p.bottom !== 0;

}

hasPadding({ color: 'black' }); // => false

hasPadding({ padding: { left: 0 } }); // => false

hasPadding({ padding: { right: 10 }}); // => true


In my opinion, this version of hasPadding() is easier to read.

7. Why like it?

I like the optional chaining operator because it allows accessing easily the properties from nested objects. It prevents writing boilerplate that verifies against nullish values on every property accessor from the accessor chain.

You can have an even better result when optional chaining is combined with a nullish coalescing operator, to handle default values more easily.

What nice use cases of optional chaining do you know? Describe it in a comment below!