Making Decisions with if
Until now, every line of your program ran every time. An if statement lets the program decide. It runs a block of code only when a condition is true:
const temp = 5;
if (temp < 15) {
console.log("Wear a coat.");
}
console.log("Have a nice day.");
Output:
Wear a coat.
Have a nice day.
The shape is: the word if, a condition in parentheses, and a block in curly braces { }. The condition can be any comparison or logic expression from the Operators section. If temp were 20, the condition would be false, and JavaScript would skip the block. The last line is outside the block, so it prints either way.
To handle the other cases, add else if for more conditions and else for "none of the above":
const score = 82;
if (score >= 90) {
console.log("A");
} else if (score >= 75) {
console.log("B");
} else if (score >= 60) {
console.log("C");
} else {
console.log("F");
}
Output:
B
JavaScript checks the conditions from top to bottom. The first true condition wins, and the rest are skipped. That is why the second test can say just score >= 75. If the program reaches that line, it already knows the score is below 90. It is also why order matters. If you test score >= 60 first, a score of 82 gets a C.
Two habits will save you from bugs:
- Always write the braces, even when the block has one line. JavaScript lets you leave them out, but then a line you add later can end up outside the
ifwithout you noticing. - Use
===in conditions, as you learned in the Operators section.
For a simple choice between two values, there is a short form called the ternary operator: condition ? valueIfTrue : valueIfFalse.
const n = 7;
const label = n % 2 === 0 ? "even" : "odd";
console.log(label);
Output:
odd
Use the ternary to pick a value. Use if when you need to run statements. Do not put a ternary inside another ternary, because it becomes hard to read.
In the exercise, finish the grade chain. The hidden tests use scores right on the boundaries, like 75 and 60.