Nullish Coalescing in JavaScript

Level 3129 keystrokes

Nullish coalescing (??) returns the right-hand value only if left is null or undefined.

JavaScript code

// null is nullish, so returns "default"
1const a = null ?? "default";
// 0 is NOT nullish (it's falsy but defined)
// So returns 0, not "default"
2const b = 0 ?? "default";
// Empty string is NOT nullish (it's falsy but defined)
// So returns "", not "default"
3const c = "" ?? "default";
// Prints "default"
4console.log(a);
// Prints 0 (differs from || which would return "default")
5console.log(b);
// Prints "" (differs from || which would return "default")
6console.log(c);

Output

default
0
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this JavaScript code and how often they appear.

  • "× 8
  • ;× 6
  • ?× 6
  • .× 3
  • (× 3
  • )× 3
  • =× 3

More JavaScript examples at level 3

← JavaScript typing practice