Handling Many Cases with else if
Introduction
In the last lesson, we used if and else to choose between two outcomes. Real programs often need more choices: a stock count might be empty, critically low, running low, or healthy. A flat chain lets us list those options clearly.
The chain is still one decision. We do not want the program to print both “critically low” and “running low” for the same count, even if both comparisons are true. Instead, JavaScript treats the branches as alternatives and stops once it finds a match. Keeping the conditions in a single chain makes that rule visible as we read the code.
We will add else if branches between if and else. JavaScript checks the chain from top to bottom, runs the first branch whose condition is true, and skips the rest. We will also see why narrow conditions often need to come before broader ones.
Add Another Condition with else if
An else if gives a chain another condition to check when the earlier condition was false. Consider the stock count below:
The first condition is false, because four is not zero. The next condition is true, so JavaScript prints Critically low. and stops checking this chain:
Only one branch in a chain runs. Even though stockCount < 20 is also true for four, JavaScript has already found a true condition earlier in the chain. The else at the end has no condition; it catches every value that did not match above.
The same tracing method works with any stored value: write down the value, test the first condition, and move to the next only if the answer is false. A value of zero immediately matches the first condition and never reaches the other comparisons. A value of twenty-five fails all three comparisons and arrives at the final else. A short trace often explains an output more clearly than rereading the whole chain at once.
Check the Branches from Top to Bottom
We can trace the chain before running it. For a count of 12, stockCount === 0 is false. Then stockCount < 5 is false. Then stockCount < 20 is true, so the running-low message appears. JavaScript does not continue to the final else:
Running the code confirms our trace:
Reading a chain this way is useful when an output surprises us. Start at the first condition, evaluate it using the current values, and move down only if it is false. Stop at the first true condition.
The order also makes the meaning of a chain easier to communicate. We can start with exceptional cases such as zero, follow with a narrow range that needs special attention, and finish with broader ranges. A condition does not have to cover every possible number by itself; the later branches fill the remaining cases. What matters is that each branch is reached only after earlier questions have failed.
