javascript
Optional Chaining in javascriptjavascriptLevel1
Progress0%
Contents
Optional Chaining in javascript
1 / 12
Introduction
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 nullWith optional chaining:
codejs
1const user = null;
2console.log(user?.name); // undefined — no errorIf the value before ?. is null or undefined, the entire expression short-circuits and returns undefined instead of throwing an error.