Doing something when the condition is false
An if statement runs its block when a condition is true. When the condition is false, the block is skipped and, by itself, nothing else happens. Often that isn't enough: you want one action when the condition holds and a different action when it doesn't.
If I'm tired:
I take a nap
Otherwise:
I start coding
In TypeScript, the "otherwise" part is an else block attached to the if:
let amTired: boolean = false;
if (amTired) {
console.log("I take a nap");
} else {
console.log("I start coding");
}
Since amTired is false, the program skips the first block and runs the one after else. It prints I start coding.
The two blocks are mutually exclusive. Exactly one of them runs, never both and never neither. That is the difference between an if-else and two separate if statements: with separate ones, both conditions are tested independently, and you must make sure they don't overlap.
An else has no condition of its own and can't appear without an if in front of it. It catches every case that the if did not.
The exercise
The starting code already has an if that handles the passing case:
let passed: boolean = false;
if (passed) {
console.log("Passed the test");
}
Because passed is false, this program prints nothing. The goal is to make it report a result in that case too.
- Find the
}that closes theifblock. Theelsegoes right after it, on the same line. - Write
else {to open the new block. - Inside, call
console.log("Failed the test");. - Close the block with its own
}.
The finished code:
let passed: boolean = false;
if (passed) {
console.log("Passed the test");
} else {
console.log("Failed the test");
}
It now prints Failed the test. If you change the first line to true, it prints Passed the test instead, and the else block is skipped.
Formatting and syntax
The lesson places } else { on one line, which is the most common style in TypeScript. Putting else on the next line also works, because whitespace between the closing brace and the keyword doesn't matter. What does matter is that the braces match up: every opening { needs a closing }, and the else must come directly after the closing brace of the if block. If another statement sits in between, the if has already ended and the else is an error.
A block can hold as many statements as you like. All of them belong to that branch, and the other branch's statements are skipped together. Both branches can also be longer than one line, so the structure scales from a single message to a whole piece of logic.
Gotchas
- Putting a condition after
else. A plainelsetakes no condition. Writingelse (passed == false)doesn't test anything: the parenthesised expression is just evaluated as the whole else branch. To test another condition, writeelse if (...). - Using two
ifs when you mean one. Twoifstatements with opposite conditions work, but they test twice, and if you change one condition and forget the other, both blocks can run, or neither. - Assuming a missing branch does nothing wrong. Without an
else, the program stays silent in the false case. That is fine when silence is what you want, and a bug when it isn't. - Typing errors in the message.
"Failed the test"and"Failed the Test"are different strings.
When both branches only assign a value, a shorter form exists: the conditional expression. With a number temp, const label: string = temp > 30 ? "hot" : "mild"; picks one of two values. Use the if-else form while you are learning, and whenever a branch holds more than one statement.
Key takeaways
elseruns when theifcondition isfalse, and has no condition of its own.- Exactly one of the two blocks runs each time.
- Write
} else {directly after the closing brace of theifblock. - An
elsecan't exist without a matchingif.