What a chain of conditionals is
An if/else pair chooses between two outcomes. Many decisions have more than two: a grade can be failing, passing, good or perfect. TypeScript handles this by inserting any number of else if branches between the if and the final else. The whole thing is one statement, called a chain.
The rule is simple. The conditions are tested from top to bottom. The first one that is true has its block run, and the rest of the chain is skipped without being evaluated. If none is true, the final else runs. The else is optional, and if you leave it out and no condition matches, nothing happens.
Syntax
let language: string = "Python";
if (language == "JavaScript") {
console.log("It's super popular!");
} else if (language == "Python") {
console.log("It's so simple!");
} else if (language == "Java") {
console.log("It's pretty hardcore!");
} else {
console.log("It's exotic!");
}
This prints It's so simple!. The first condition is false, so the chain moves on. The second is true, so its block runs, and the Java check is never evaluated. Set language to "Go" and every condition is false, so the final else prints It's exotic!.
Write the braces even when a block holds one line. The language allows leaving them out, but a second line added later is then easy to misplace.
Order matters
Because only the first true branch runs, the order of the branches is part of the logic. Each branch can rely on every earlier condition having been false. That lets you write ranges with only one bound:
function check(n: number): void {
if (n > 0) {
console.log("first");
} else if (n > 10) {
console.log("never");
} else {
console.log("other");
}
}
check(20);
check(-1);
first
other
Here n > 10 can never be reached with a true result: any number above 10 is also above 0, so the first branch already caught it. When a branch seems to be ignored, check whether an earlier, broader condition is catching its values. Put the most specific condition first.
A chain is not a series of separate ifs
Compare the chain with separate if statements:
let g2: number = 4;
if (g2 < 5) console.log("fail");
if (g2 <= 7) console.log("pass");
fail
pass
Each if here is tested on its own, so both messages print. Joined with else if, only the first would. Use a chain when the outcomes are mutually exclusive.
Gotchas in TypeScript
- Prefer
===to==. The loose==converts types before comparing, so the number5and the string"5"count as equal.===compares without converting. TypeScript's type checker also catches many such comparisons at compile time, but the types are erased in the generated JavaScript, so===is the safer habit. - Write
else ifas two words. There is noelseifkeyword. - A stray semicolon ends the statement.
if (x > 3);followed by a block makes the block run unconditionally. - Don't forget the final
elsewhen you need a fallback. Without it, values outside every range produce no output at all.
The lesson's exercise
The code starts with let grade: number = 8; and the task is to print a message for each range of grades. Build the chain one branch at a time.
- Start with the failing case. An
ifchecksgrade < 5and logs"Failed the test". Handling the lowest grades first lets every later branch assume the grade is at least 5. - Add an
else ifforgrade <= 7. It logs"Passed the test". The comparison is "less than or equal" because 7 itself belongs here. There is no lower bound to write, since grades below 5 were already caught. - Add one more
else ifforgrade <= 9. It logs"Good Job", again with no lower bound. - Close the chain with
else. It has no condition. It logs"Perfect"for everything above 9.
let grade: number = 8;
if (grade < 5) {
console.log("Failed the test");
} else if (grade <= 7) {
console.log("Passed the test");
} else if (grade <= 9) {
console.log("Good Job");
} else {
console.log("Perfect");
}
With grade equal to 8, the first two conditions are false and the third is true, so the output is Good Job. Try the values 4, 7, 9 and 10 in the editor above: they print Failed the test, Passed the test, Good Job and Perfect. The boundary values 7 and 9 are the ones worth checking, because they test the <= comparisons.
Key takeaways
- A chain tests its conditions from top to bottom and runs only the first block whose condition is true.
- Later branches can rely on the earlier conditions being false, so they need only one bound.
- Put the most specific conditions first, and finish with an
elsefor everything else. - Separate
ifstatements are independent. Onlyelse ifmakes the outcomes exclusive. - Use
===for comparisons, and decide boundary values (<or<=) deliberately.