JavaScript Runtime Semantics

Truthiness & Control Flow

JavaScript conditionals evaluate truthiness, not only booleans. This is convenient for presence checks, but dangerous when 0, false, or an empty string are valid values.
  • Falsy values are a small fixed set
  • Truthiness is not the same as existence
  • ?? checks nullishness only
  • || falls back for any falsy value
  • Control flow affects TypeScript narrowing
Defaulting operators
ExpressionFalls back whenPreserves 0/false/''?
value || fallbackAny falsy valueNo
value ?? fallbacknull or undefinedYes
condition ? a : bExplicit conditionDepends on condition
Defaulting bug
function pageSize(input) {
  return input || 20
}

pageSize(0) // 20, maybe wrong

function pageSizeSafe(input) {
  return input ?? 20
}

pageSizeSafe(0) // 0
Use `??` when zero, false, or empty string are valid values.
Sources
  • MDN JavaScript Guide and ReferenceControl flow and error handling
  • The Modern JavaScript TutorialType conversions and conditionals
  • ECMAScript Language SpecificationToBoolean