Skip to main content

Working with Data

Optional Chaining and Nullish Coalescing

0:00
LearnStep 1/3

Modern Safe Access and Defaults

JavaScript introduced two powerful operators in ES2020 to handle nullable values more elegantly: Optional Chaining (?.) and Nullish Coalescing (??).

Optional Chaining (?.)

The optional chaining operator accesses a property or calls a function only if the operand before it is not null or undefined. If it is, the expression short-circuits and returns undefined immediately, avoiding the dreaded TypeError: Cannot read properties of undefined.

javascript

Nullish Coalescing (??)

The nullish coalescing operator returns the right-hand side operand only when the left-hand side is null or undefined. This is distinct from the logical OR operator (||), which returns the right side for any falsy value (like 0, '', or false).

javascript

Combining Both

These operators are often used together to safely extract a value or fallback to a default if the path doesn't exist.

javascript