Member-only story

Simplify Your Code with Optional Chaining (?.) in JavaScript

Discover how optional chaining can make working with nested objects less error-prone and improve readability

Max N
3 min readMar 15, 2024

Working with deeply nested objects in JavaScript often requires multiple property accesses, which may result in errors if any part along the chain doesn’t exist. To mitigate such issues, developers might check each level before proceeding further down the chain.

However, this approach introduces additional complexity and reduces code readability. Enter optional chaining — an elegant solution to tackle this challenge, brought to us by ECMAScript 2020 (ES11).

Let’s dive deep into understanding optional chaining and learn how to utilize it efficiently.

What is Optional Chaining?

Optional chaining (?.) provides a concise way to handle potential undefined or null values while traversing complex object hierarchies. Instead of throwing exceptions, it simply returns undefined whenever there are missing properties or chains in the path.

Its primary purpose is reducing repetitive checks against undefined or null references, thereby improving both safety and maintainability.

Basic Usage

--

--

Max N
Max N

Written by Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.

No responses yet