Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Default if Nullish

Fundamentals: Part 1medium

Course · Section 2: JavaScript Fundamentals – Part 1 · Lecture 11: Data Types

Implement `withDefault(value, fallback)` returning `value` unless it is null or undefined, in which case return `fallback`. Note that `0` and empty string are valid values.

Sample tests

Input: withDefault(null, 5)
Output: 5
Input: withDefault(0, 5)
Output: 0

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Using || here would wrongly replace 0 or empty string with the fallback.

Learning resources

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

?? treats only null and undefined as missing, so valid falsy values like 0 are preserved unlike with ||.

Loading...
⌘/Ctrl + Enter

Run your code to see results.