JS-041
Nullish Coalescing  explained in a JavaScript learning illustration — A fallback value
Beginner4 min~4 min read#nullish#coalescing#fallback

Nullish Coalescing ??

A fallback value

Goal

Learn to use ?? to provide a fallback value when data is missing.

Explanation

  • The ?? operator is called Nullish Coalescing.
  • It returns the left-hand value if that value exists.
  • If the left-hand value is null or undefined, it returns the right-hand value.
  • ?? is often used to provide default values.
  • It is a convenient way to supply a fallback.

Analogy

If a door has no nameplate, you put up one that says “Guest.” If a name is present, you use it.

Code

let username = null;

console.log(username ?? "Guest");
console.log("Vitalii" ?? "Guest");

Result: Guest Vitalii

Common mistake

Beginners confuse ?? with ||. The ?? operator responds only to null and undefined.

Remember

  • ?? works with null and undefined.
  • If a value is present, that value is used.
  • If a value is missing, the fallback is used.

Quick Quiz

What does null ?? "Guest" return?

Resources