JavaScript AcademyProfessional Engineering
Level 1 · FoundationsModule 3: Decisions and LogicLesson 13 of 150About 45 minutes

Lesson 13: If, else if and else

01Opening question

A grading app turns 87 into a B. How does a program choose one path out of several?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

Conditions are checked top to bottom. The first true one runs, and the rest are skipped.

const score = 87;
if (score >= 90) {
  console.log("A");
} else if (score >= 80) {
  console.log("B");
} else {
  console.log("Keep practising");
}

03Objective and prerequisites

Learning objective: Write if, else if and else statements, order conditions correctly, use blocks and guard clauses, and avoid assignment-instead-of-comparison mistakes.

You need: Lesson 11: Comparison operators, Lesson 12: Logical operators

Skills practised: Logic, Conditional statements.

04Explanation

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.

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.

Open the full glossary

06Visual learning object

Conditional decision tree. Step through an if / else if / else chain and watch which conditions are checked and which branch runs.

Loading the interactive object…

Open the full Conditional decision tree page with its guided experiment.

07Examples

ex-013-01if and else Browser-executable JavaScript

One of the two blocks always runs.

const stock = 0;
if (stock > 0) {
  console.log("In stock:", stock);
} else {
  console.log("Sold out");
}
Sample input
None
Expected output
Sold out
Common mistake
Putting a semicolon after if (...) which ends the if immediately.
Try this
Set stock to 5 and run again.
Source
examples/ex-013-01-if-else.js

ex-013-02An else if chain Browser-executable JavaScript

Only the first matching branch runs, so the thresholds go from highest to lowest.

const score = 74;
let grade;
if (score >= 90) {
  grade = "A";
} else if (score >= 80) {
  grade = "B";
} else if (score >= 70) {
  grade = "C";
} else {
  grade = "Not yet";
}
console.log(`Score ${score}: ${grade}`);
Sample input
None
Expected output
Score 74: C
Common mistake
Ordering thresholds from lowest to highest, so everyone gets the first branch.
Try this
Add a D band for scores of 60 or more.
Source
examples/ex-013-02-grade-chain.js

ex-013-03When the order is wrong Browser-executable JavaScript

The first condition is too general, so the later ones can never run.

const total = 120;
if (total >= 50) {
  console.log("Free shipping");
} else if (total >= 100) {
  console.log("Free shipping and a gift");
}
Sample input
None
Expected output
Free shipping
Common mistake
Checking the broader condition first.
Try this
Swap the two conditions so a total of 120 receives the gift.
Source
examples/ex-013-03-wrong-order.js

ex-013-04Check the invalid cases first Browser-executable JavaScript

Handling bad input first keeps the main calculation simple.

const quantityText = "abc";
const quantity = Number(quantityText);
if (quantityText.trim() === "") {
  console.log("Please enter a quantity");
} else if (Number.isNaN(quantity) || quantity < 1) {
  console.log("Quantity must be a positive number");
} else {
  console.log("Line total:", quantity * 25);
}
Sample input
None
Expected output
Quantity must be a positive number
Common mistake
Calculating first and validating afterwards.
Try this
Try "3", "" and "-2".
Source
examples/ex-013-04-guard-first.js

08Guided exercises

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);

More cases in the Debugging Detective Laboratory

11Practical scenario

Grading and pricing tables

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

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

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.

16AI learning prompts

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 explanation if / 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 prediction Branch 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.
Debugging Wrong 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 generation Pricing 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 review Nested 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.