Programming Languages

JavaScript ?? vs ||: Keep Zero When Zero Is a Valid Value

Huwell Consultancy editorial2 min read

A fallback value can quietly change valid input. If zero is a meaningful value, using logical OR may not do what you intended. The nullish coalescing operator, ??, answers a narrower question.

Compare the results

console.log(0 || 10);        // 10
console.log(0 ?? 10);        // 0
console.log("" ?? "default"); // ""
console.log(null ?? 10);     // 10

Logical OR uses the fallback for falsy values. Nullish coalescing uses it when the left value is null or undefined. MDN explains this distinction. An empty string, false or zero can therefore be preserved by ?? when those values are valid for your application.

Start with a requirement

Imagine an optional retry-count setting. If a user supplies zero to mean no retries, replacing it with a default of three changes the requested behaviour. If an empty string should be rejected, however, ?? is not a substitute for validation. Decide which values are acceptable before choosing an operator.

Make a small test list

  • Zero.
  • A positive number.
  • Null.
  • Undefined.
  • An empty string if the input can contain text.

Write the expected result for each case and distinguish a missing value from an incorrect value. A fallback should not silently turn every invalid input into something plausible.

Explain it simply

For a Malta frontend interview, describe what “missing” means in the feature. The useful explanation is not that one operator is always better; it is that the chosen operator preserves the behaviour you actually want.

Sources and further reading

Browse current technology jobs in Malta →

EXPLORE THE NEXT STEP

Discuss the work you want to do.

Browse current technology vacancies with Huwell Consultancy and ask us about the responsibilities that matter to you.

Explore opportunities
KEEP EXPLORING

More guidance for your next decision