javascript
javascript
Optional Chaining in javascript
Live
bolt
Level1
Progress0%

Optional Chaining in javascript

CARD 1

Introduction

Login to report note issues for this section.

Optional Chaining — ?.

Optional chaining (?.) is a safe way to access deeply nested properties of an object without throwing an error if an intermediate property does not exist or is null or undefined.

Without optional chaining, accessing a property on null or undefined throws a TypeError:

codejs
1const user = null;
2console.log(user.name); // TypeError: Cannot read properties of null

With optional chaining:

codejs
1const user = null;
2console.log(user?.name); // undefined — no error

If the value before ?. is null or undefined, the entire expression short-circuits and returns undefined instead of throwing an error.