Ad space (banner)
🟨JavaScript Lessons
Lesson 22 / 69

Null-Safe Syntax (?? and ?.)

In this lesson you'll learn JavaScript's null-safe syntax (?? and ?.) so you can safely handle data that might not exist. This is for people searching "JavaScript optional chaining usage" or "JavaScript null vs undefined."

?? (the nullish coalescing operator) uses the value on its right only when the left side is null or undefined. ?. (optional chaining) returns undefined instead of throwing an error when a value doesn't exist. These are powerful for situations where data might be missing — for example, "if an address hasn't been registered, don't stop with an error; show 'not set' instead." It's a relatively new piece of syntax, but it's now a staple of modern code.

The sample code shows that even when user.address is null, user.address?.city doesn't throw an error and just returns undefined, which is then replaced with a fallback string via ?? "no address set". Combining ?. and ?? lets you safely access a "property that may or may not exist" while also providing a fallback display, all at once.

A common beginner stumbling block is the difference between ?? and ||. || falls back to the right side even when the left side is a "falsy value" like 0 or an empty string "", but ?? only falls back for null and undefined. In a case like "I still want to display 0 when the score is 0 points," you need to use ??, or you'll get an unintended result.

In real development, it's not unusual for some of the data coming back from an API to be missing. Mastering optional chaining and the nullish coalescing operator lets you write safe code without an if statement checking for existence at every turn — a practical technique valued for preventing app crashes caused by errors.

JavaScript
OUTPUT

💡 Anything passed to console.log() appears in the output below.

Ad space (banner)
Ad space (in-article)