Why programs need decisions
Programs rarely run the same lines every time. They look at a situation and choose what to do, just as you would: if it is raining, you take an umbrella; if you are hungry, you eat. An if statement is how TypeScript expresses that choice.
if (condition) {
// runs only when the condition is true
}
The keyword if is followed by a condition in parentheses and a block of code in curly braces. The block runs only when the condition is true. When it is false, the program skips the block and continues after it.
Boolean conditions
The condition is a Boolean value, which means it is either true or false. A variable can hold one directly, and comparisons such as age >= 18 produce one.
let isRainy: boolean = true;
if (isRainy) {
console.log("I bring an umbrella");
}
This prints I bring an umbrella, because isRainy is true. With the opposite value, nothing is printed at all:
let amHungry: boolean = false;
if (amHungry) {
console.log("I have breakfast");
}
A condition that is already a Boolean doesn't need a comparison. Write if (isRainy), not if (isRainy == true); both work, but the short form is the usual one.
Several decisions in a row
A program can hold any number of if statements, and each one is judged on its own. Take the three decisions from a typical day:
let isRainy: boolean = true;
let amHungry: boolean = false;
let amTired: boolean = true;
if (isRainy) {
console.log("I bring an umbrella");
}
if (amHungry) {
console.log("I have breakfast");
}
if (amTired) {
console.log("I take a nap");
}
console.log("Done");
The output is:
I bring an umbrella
I take a nap
Done
The second block is skipped, and the last line runs no matter what, because it sits outside every if. Code after a block simply continues once the decision has been made.
Conditions are often comparisons. With let age: number = 20;, the condition age >= 18 is true, so a block guarded by it would run.
The exercise
The starting code has a Boolean variable:
let passed: boolean = true;
The program should print one message when passed is true and a different one when it is false. It takes three steps.
- Write the
if. Typeif (passed) {. The condition is just the variable, because it is already a Boolean. - Add the success message. Inside the block, call
console.log("Passed the test");. These lines run only whenpassedis true. - Add an
else. Close the block with} else {on one line, print"Failed"inside, and close with}. Anelseblock has no condition of its own. It runs whenever theifcondition was false.
The finished code:
let passed: boolean = true;
if (passed) {
console.log("Passed the test");
} else {
console.log("Failed");
}
With passed set to true, it prints Passed the test. Change the first line to false and it prints Failed. Exactly one of the two blocks runs each time.
Gotchas
- A single equals sign assigns.
if (passed = false)setspassedtofalseand then tests that value, so it doesn't compare anything. Comparisons use==or===. - Not only Booleans work as conditions. JavaScript treats some other values as false:
0, the empty string,null,undefinedandNaN. Everything else, including an empty array and the string"false", counts as true. A number-typed variable can therefore be used inif (count), but that quietly treats0as "no". Write the comparison you mean, such ascount > 0. - Skipping the braces. A single statement can follow
ifwithout braces, but then only that one statement is conditional, and adding a second line later is a classic source of bugs. Keeping the braces is safer. - Misplaced parentheses or braces. The condition needs its parentheses, and every
{needs a matching}. The compiler reports an error if one is missing. - Printing with the wrong text. The messages are compared as written, so
"Passed the test"and"Passed the Test"are different strings.
Key takeaways
- An
ifstatement runs its block only when the condition in parentheses istrue. - The condition is a Boolean value or any expression that produces one.
elsecovers every case theifdid not, and has no condition.- Use a comparison to say what you mean, rather than relying on values such as
0counting as false.