So far your programs ran every line, top to bottom. With if, a program can choose.
const temperature = 31;
if (temperature > 30) {
console.log("It is hot today.");
}
The part in brackets is a condition. If it is true, the code inside the curly braces runs. If it is false, that code is skipped.
Comparisons
A condition is usually a comparison, and a comparison is always either true or false. Those two values are called booleans.
| Operator | Meaning |
|---|---|
> and < | greater than, less than |
>= and <= | greater or equal, less or equal |
=== | equal to |
!== | not equal to |
Use three equals signs to compare. One = stores a value, it does not compare. Mixing them up is a classic bug.
else and else if
else gives the code to run when the condition is false. else if adds more conditions in between. JavaScript checks them in order and runs only the first one that is true:
if (temperature > 30) {
console.log("Hot");
} else if (temperature > 15) {
console.log("Nice");
} else {
console.log("Cold");
}
Combining conditions
&&means and: both sides must be true.||means or: at least one side must be true.!means not: it flips true and false.
if (age >= 13 && age <= 19) {
console.log("Teenager");
}
Your Task
- Write an
if/else if/elsechain that sets the variablegradefromscore: "A"when the score is 90 or more,"B"when it is 75 or more,"C"for anything lower.- Print
grade. Then changescoreat the top to a few other numbers and run it again to test every branch.
- The code uses
if,else ifandelse gradeis correct for the score at the top of your code- The chain gives A for 95, B for 75 and C for 40
- The grade is printed
Lesson complete!
Next Lesson: Loops