View profile

Optional Chaining (AKA The Elvis Operator) in JavaScript

The optional chaining operator hit stage 3 in TC39 this week, which means the spec is complete and re
Optional Chaining (AKA The Elvis Operator) in JavaScript
The optional chaining operator is also called the safe navigation operator. The general idea of the optional chaining operator is to let you access deeply nested properties without checking if each intermediate property is undefined. For example, consider the below expression.

What could possibly go wrong here?
What could possibly go wrong here?
Seems simple enough. But what if landmark, landmark.location, or landmark.location.geometry is undefined? JavaScript will throw a TypeError. Your alternatives are to use Lodash’s get function, or to explicitly check every intermediate path.
Safety shouldn't be this hard
Safety shouldn't be this hard
The optional chaining operator `?.` lets you skip checking intermediate paths. That’s because the optional chaining operator short-circuits and evaluates to undefined if its left hand side (LHS) is null or undefined. The below expression will not throw an error if landmark, landmark.location, or landmark.location.geometry is null.
No TypeErrors here
No TypeErrors here
This Week's Tutorials
Did you enjoy this issue?
Mastering JavaScript Tutorials

Mastering JavaScript Tutorials

If you don't want these updates anymore, please unsubscribe here
If you were forwarded this newsletter and you like it, you can subscribe here
Powered by Revue