When does JavaScript use the `else` branch of an `if` statement?
Quick answer
JavaScript runs an if block when its condition is truthy and the optional else block when the condition is falsy. Zero is falsy, so if (0) takes the else branch. Other falsy values include false, null, undefined, NaN, and the empty string. [S1]
The question, the details, the next step.
A practical checklist
Identify the expression inside
if (...).Determine whether that expression is truthy or falsy.
If the condition is falsy, the
elsebranch runs when present. [S1]Remember that
0,false,null,undefined,NaN, and the empty string are falsy. [S1]Check whether truthiness groups values that your program needs to distinguish.
A few more useful answers
Does `else` run only when the condition is the number zero?
No. It runs when the condition is falsy. Zero is one example; false, null, undefined, NaN, and the empty string are also listed as falsy values. [S1]
If the condition is `false`, does the `else` branch run?
Yes. false is a falsy value, so it selects the else branch when one is present. [S1]
What if there is no `else` block?
The else branch is optional. If there is no else block, there is no alternate block to run when the condition is falsy.
Sources
References used for this guide.
- [S1] if...else — JavaScript | MDN developer.mozilla.org · Checked
