7 / 12 · Intro
Making decisions with if and else in JavaScript
An if statement runs a block of code only when its condition is true. With else if, JavaScript checks conditions from the top and stops at the first true one.
Jump to the 10 practice questionsYou will learn
- Run a block only when its condition is true
- Choose between paths with else and else if, in the right order
- Pick between two values with the conditional operator
Before this: Booleans and comparisons
1Explain
Run code only sometimes
The condition goes in parentheses after the word if. It is any expression that produces a boolean, usually a comparison from the last unit. The code to run when it is true goes inside curly braces, which form a block. If the condition is false, JavaScript skips the whole block and carries on after the closing brace.
Watch which lines run: the block inside the braces runs only because 31 >= 30 is true, and "Done" prints either way.
const temperature = 31;if (temperature >= 30) {console.log("Hot day. Drink water.");}console.log("Done");
Hot day. Drink water. Done
2Explore
Change the temperature
Below 30 the block is skipped; from 30 up it runs. The last line is outside the braces, so it always runs.
const temperature = 18;
if (temperature >= 30) {
console.log("Hot day. Drink water.");
}
console.log("Done");Done3Problem
A skipped block
What does this print?
const x = 2;
if (x > 3) {
console.log("big");
}
console.log("end");Hint
Is 2 > 3 true? Which line is outside the braces?
Solution
Answer: Only end
The condition is false, so the block is skipped; the last line always runs.
4Explain
else: the other path
Often you want one thing when the condition is true and something else when it is false. Add an else block. Exactly one of the two blocks runs, never both and never neither.
const n = 7;
if (n % 2 === 0) {
console.log(n + " is even");
} else {
console.log(n + " is odd");
}
// prints: 7 is odd7 is odd5Explain
else if: more than two choices
For several possibilities, chain conditions with else if. JavaScript tests them from the top. As soon as one is true it runs that block and skips all the rest, even if later conditions would also be true. The final else catches everything that matched nothing above.
JavaScript tests the conditions from the top and stops at the first true one; the other blocks are skipped.
const score = 72;if (score >= 90) {console.log("A");} else if (score >= 80) {console.log("B");} else if (score >= 70) {console.log("C");} else {console.log("F");}// prints: C
C
6Explore
Grade any score
Slide the score across 70, 80 and 90 and see where the grade changes.
const score = 72;
if (score >= 90) {
console.log("A");
} else if (score >= 80) {
console.log("B");
} else if (score >= 70) {
console.log("C");
} else {
console.log("F");
}C7Problem
A chain in the wrong order
const s = 95;
if (s >= 70) {
console.log("C");
} else if (s >= 90) {
console.log("A");
}Hint
Read from the top. Is 95 >= 70 true?
Solution
Answer: C
The first true condition wins. 95 >= 70 is true, so the A branch is never checked.
8Problem
The conditional operator
When you only need to pick between two values, there is a compact form called the conditional (ternary) operator: condition ? valueIfTrue : valueIfFalse. For example, const label = n % 2 === 0 ? "even" : "odd";. Use it for short choices of a value. For anything that runs several statements, a normal if and else is clearer.
const n = 10;
console.log(n > 5 ? "yes" : "no");Hint
When the condition is true, the value before the colon is chosen.
Solution
Answer: yes
The condition is true, so the value before the colon is chosen.
9Practice
Add the B and C grades
Add else if branches so 80 or more prints B and 70 or more prints C. With score 72 the program should print C.
Cconst score = 72;
if (score >= 90) {
console.log("A");
} else {
console.log("F");
}
Hint
Put the two else if branches between the if and the else, highest score first.
A solution
const score = 72;
if (score >= 90) {
console.log("A");
} else if (score >= 80) {
console.log("B");
} else if (score >= 70) {
console.log("C");
} else {
console.log("F");
}10Practice
Ticket price by age
Use if and else if to set price from the rules in the comment. For age 10 it should print Price: 5.
Price: 5const age = 10;
let price = 12;
// Under 13 pays 5.
// 65 and over pays 6.
// Everyone else pays 12.
console.log("Price:", price);
Hint
Change price inside the branches with price = 5; and do not declare it again there.
A solution
const age = 10;
let price = 12;
if (age < 13) {
price = 5;
} else if (age >= 65) {
price = 6;
}
console.log("Price:", price);11Problem
0 as a condition
let msg = "start";
const n = 0;
if (n) {
msg = "nonzero";
}
console.log(msg);Hint
0 counts as false in a condition.
Solution
Answer: start
0 is falsy, so the block is skipped and msg keeps its first value.
12Explain
Common mistakes
const score = 100;
if (score = 100) {
console.log("Full marks");
}TypeError: Assignment to constant variable. (line 2)
- The word before the colon names the kind of error: ReferenceError, TypeError, SyntaxError.
- After the colon: what went wrong, usually with the name involved.
- The line number shows where the program stopped. A SyntaxError stops it before any line runs.
One = stores a value instead of comparing. Here score is a const, so JavaScript stops; with let the condition would quietly be true every time. Compare with ===.
const n = 7;
if (n > 5) {
console.log("big");SyntaxError: Unexpected end of input
- The word before the colon names the kind of error: ReferenceError, TypeError, SyntaxError.
- After the colon: what went wrong, usually with the name involved.
- The line number shows where the program stopped. A SyntaxError stops it before any line runs.
A missing closing brace: the code ends while the block is still open.
13
Summary
- if (condition) { ... } runs the block only when the condition is true.
- else runs when it is false; exactly one of the two runs.
- else if chains are checked from the top; the first true one wins.
- Put the narrowest condition first when ranges overlap.
- Compare with ===, never a single =.