Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Nullish Coalescing

Fundamentals: Part 1easy

Course · Section 2: JavaScript Fundamentals – Part 1 · Lecture 13: Basic Operators

Implement `coalesce(a, b)` returning `a` when it is neither null nor undefined, otherwise `b`.

Sample tests

Input: coalesce(null, 3)
Output: 3
Input: coalesce(0, 3)
Output: 0

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • || would also replace 0, '' and false, which ?? does not.

Learning resources

  • MDN: Expressions and operators
Visualize this concept: Data Types and Coercion →
Approach & explanation (try first)

Nullish coalescing keeps a unless it is null or undefined, unlike || which also rejects other falsy values.

Loading...
⌘/Ctrl + Enter

Run your code to see results.