Learning objective: Write if, else if and else statements, order conditions correctly, use blocks and guard clauses, and avoid assignment-instead-of-comparison mistakes.
An if statement runs a block of code only when its condition is truthy: if (stock === 0) { console.log("Sold out"); }.
Add else for what happens otherwise, and else if for more choices. JavaScript checks the conditions in order and runs only the first block whose condition is true.
Order matters: check the most specific or highest threshold first. If score >= 50 came before score >= 90, everyone with 90 would get the 50 message.
Use === inside conditions. A single = assigns a value instead of comparing, and if (x = 5) is always true.
if evaluates its condition with ToBoolean, so truthiness rules apply. Being explicit (if (items.length > 0)) avoids misreading.
Guard clauses (early returns) reduce nesting: handle invalid cases first and return, so the main path is not indented. In top-level scripts you can do the same with if/else chains.
Braces are optional for single statements but leaving them out invites bugs when a second line is added; most style guides require them (curly).
Blocks create scope for let and const: variables declared inside an if block do not exist after it.
05Definitions
if statement
Runs a block only when its condition is true.
else
The block that runs when no earlier condition was true.
else if
An extra condition checked when the previous ones were false.
Block
Statements grouped in { } that run together.
Guard clause
An early check that handles an invalid case first so the main code stays simple.
Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.
Comparison, not assignment
Spot = used instead of === in a condition.
let status = "pending";
if (status = "shipped") {
console.log("Your parcel is on its way");
} else {
console.log("Your order is being prepared");
}
Shipping cost bands
Complete an else if chain in the right order.
const total = 65;
let shipping;
// TODO: total of 100 or more: 0
// total of 50 or more: 4.99
// anything else: 9.99
console.log("Shipping:", shipping);
Cinema ticket pricing
Design a decision chain from a pricing table.
const age = 67;
const isTuesday = true;
// Prices: under 12 → 6; 65 and over → 7; everyone else → 11.
// On Tuesdays every ticket is 2 cheaper.
09Prediction
Commit to an answer first, then run the real code to compare.
const temp = 18;
if (temp > 25) {
console.log("hot");
} else if (temp > 15) {
console.log("mild");
} else if (temp > 5) {
console.log("cool");
}
console.log("done");
What is printed?
10Debugging investigation
Every customer is Bronze
A loyalty program has Gold (1000+ points), Silver (500+) and Bronze (100+). A customer with 1,250 points is shown as Bronze.
const points = 1250;
let tier = "None";
if (points >= 100) {
tier = "Bronze";
} else if (points >= 500) {
tier = "Silver";
} else if (points >= 1000) {
tier = "Gold";
}
console.log("Tier:", tier);
Business rules often come as tables: price bands, grade boundaries, shipping zones. An else if chain mirrors the table, and the order of the rows decides correctness.
const kg = 3;
let cost;
if (kg > 10) cost = 20; else if (kg > 2) cost = 8; else cost = 4;
console.log(cost);
12Knowledge check
1. What does this print?
const n = 5;
if (n > 10) { console.log("big"); } else { console.log("small"); }
big
small
big and small
nothing
2. In an else if chain, how many blocks can run?
All true ones
At most one
Exactly two
Always all
3. Why does every order print "Large"?
let size = "S";
if (size = "L") { console.log("Large"); }
The numbers are wrong
if (size = "L") assigns instead of comparing
Strings cannot be compared
else is missing
4. What does this print?
const s = 85;
if (s >= 90) console.log("A");
else if (s >= 80) console.log("B");
else console.log("C");
A
B
C
A then B
5. Which ordering is correct for discounts (>= 100 → 20%, >= 50 → 10%)?
Check >= 50 first
Check >= 100 first
Order does not matter
Use two separate ifs without else
6. What is a guard clause?
A loop
An early check for an invalid case
A kind of comment
A security feature
13Solutions and tests
Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.
Automated acceptance tests for this lesson
These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.
Comparison, not assignment: Prints the preparing message; status is unchanged
Shipping cost bands: Prints Shipping: 4.99; Uses else if; Checks the 100 band before the 50 band (extra case)
Cinema ticket pricing: Prints Ticket: 5; price is 5; Uses an if chain and a separate Tuesday check
ex-013-01: output matches the documented expected output
ex-013-02: output matches the documented expected output
ex-013-03: output matches the documented expected output
ex-013-04: output matches the documented expected output
The lesson lives in the companion repository at curriculum/level-01-foundations/module-03-decisions-and-logic/lesson-013-if-else-if-and-else/. Every example on this page is generated from those files.
These links open the files in the GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Engineering-Academy). You can also use the ZIP download above.
15Summary and next steps
if runs a block when its condition is true; else handles the rest.
else if chains run only the first true branch, so order thresholds carefully.
Use === in conditions; = assigns.
Handle invalid input first to keep the main path simple.
Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.
Concept explanationif / else if / else
Context: I am learning conditionals.
Task: Explain if, else if and else using a parcel tracking example.
Constraints: Beginner level.
Expected behaviour: I can predict which branch runs.
Testing: Give me three inputs to trace.
Code predictionBranch tracing
Context: I can read else if chains.
Task: Give me five chains with an input and ask which branch runs.
Constraints: Wait for answers.
Expected behaviour: Each has one answer.
Testing: Explain ordering mistakes.
DebuggingWrong branch
Context: My grading program gives everyone the lowest grade.
Task: Help me find the ordering or comparison problem.
Constraints: Questions first.
Expected behaviour: I fix the chain myself.
Testing: Suggest boundary values to test (59, 60, 89, 90).
Exercise generationPricing tables
Context: I finished the cinema pricing exercise.
Task: Create two exercises from pricing tables.
Constraints: Exact expected output for given inputs.
Expected behaviour: Each has at least three bands.
Testing: Include expected outputs for three inputs.
Code reviewNested if review
Context: My validation code has ifs nested four levels deep.
Task: Show me how guard clauses could flatten it.
Constraints: Keep behaviour identical.
Expected behaviour: No more than two levels of nesting.
Testing: Give tests that show the behaviour is unchanged.