Making decisions with if
You'll learn to make code choose what to do with if, else if and else.
Watch & read
Start with the required ones. The others are there when you need them.
Explanation
You want your code to do different things in different cases. If the balance is too low, show a warning. Otherwise, let the payment go through.
A question with a yes or no answer is called a condition. It gives true or false. if runs its
block only when the condition is true:
const marks = 72;if (marks >= 80) {console.log("A+");} else if (marks >= 70) {console.log("A");} else {console.log("Keep going");}
JavaScript checks the conditions from top to bottom and runs only the first one that is true. Here
72 >= 80 is false, 72 >= 70 is true, so it prints A and skips the rest. else catches everything
left over.
To compare, use >, <, >=, <=, === (equal) and !== (not equal). Always use three equals signs.
== tries to convert types first, so 5 == "5" is true. 5 === "5" is false, which is usually what
you mean.
To join conditions, use && (and: both must be true), || (or: at least one is true), and ! (not:
flips true and false). marks >= 33 && attended is true only when both parts are true.
if also accepts values that are not true or false. A few count as false: 0, "" (empty text),
null, undefined and NaN. Everything else counts as true. So if (name) means "if name is not
empty".
People often put the conditions in the wrong order. If you check marks >= 70 before marks >= 80, a
95 stops at the first one and never gets an A+. Put the strictest check first.
When you read an if chain, pick a value and walk down it. Stop at the first condition that is true.
Code tour
Click a line number with a ring to read the note for that line.
Practice
Short drills. Take your time and read the code before you answer.
1const balance = 300;2if (balance > 500) {3 console.log("Buy the AC seat");4} else if (balance > 200) {5 console.log("Buy the normal seat");6} else {7 console.log("Save more first");8}
grade should give "A+" for 80 and above, "A" for 70 to 79, "Pass" for 33 to 69, and "Fail" below 33. The first and last lines wrap the code so we can test many marks; you'll learn about functions soon. Fix only the if chain.Quick check
3 questions. Each one explains itself after you answer.
- 1 / 3What is
5 === "5"? - 2 / 3With
const balance = 300; const pinOk = false;, what isbalance > 100 && pinOk? - 3 / 3With
const marks = 90;, which line prints?if (marks >= 33) { console.log("Pass") } else if (marks >= 80) { console.log("A+") }
Explain it back
How confident are you with Making decisions with if?
Done
if / else if chain and say which branch runs for a given value.