SECTION 1
Historical Context & Motivation
Every program you use — from social media apps to video games — makes thousands of decisions every second. Should the character jump or fall? Should the notification appear or stay hidden? At the heart of all these choices lies a concept called conditional branching, the ability for code to follow different paths depending on whether something is true or false. The if/else chain is the most fundamental tool programmers use to implement this kind of decision-making logic.
The idea of conditional logic in computing has a fascinating history. Long before JavaScript existed, mathematicians and engineers developed formal systems for handling decisions. Understanding this history helps explain why if/else chains look the way they do in modern code.
1847 • Boolean Algebra is Born
1946 • ENIAC and Conditional Branching
1957 • Fortran's IF Statement
1972 • C Language Formalizes if/else
1995 • JavaScript Adopts if/else
The core question that if/else chains answer is straightforward: how can a program choose between multiple possible actions based on the current situation? Without conditional branching, every program would execute the exact same instructions every time, making interactive software impossible. Let's explore how JavaScript's if/else chains give us this power.
SECTION 2
Core Principles & Definitions
Before diving into code, you need to understand a few foundational ideas. An if/else chain is built from simple building blocks, and mastering each one will make the whole structure feel natural. Every chain starts with a condition — an expression that JavaScript evaluates to either true or false. Based on that result, the program decides which block of code to run.
The if Block
if keyword tests a condition inside parentheses. If the condition is true, the code inside the curly braces runs. If it's false, JavaScript skips that block entirely.The else Block
else block is the catch-all. It runs only when the preceding if condition (and any else if conditions) were all false. It requires no condition of its own.The else if Block
else if lets you test additional conditions after the initial if. You can chain as many else if blocks as you need, and JavaScript checks them in order from top to bottom.Short-Circuit Evaluation
else if and else blocks are skipped entirely.Boolean Coercion
0, "", null, and undefined are treated as falsy; most other values are truthy.KEY TAKEAWAY
else block is the emergency exit at the end that's always unlocked. JavaScript never executes more than one branch in a single if/else chain.SECTION 3
Visual Explanation — How If/Else Chains Flow
A flowchart is the best way to visualize how JavaScript evaluates an if/else chain. The diagram below shows a grading system that assigns a letter grade based on a numeric score. Notice how the program tests each condition in order and follows only one path to a single output.
This diagram illustrates a critical rule: only one branch ever executes. If a student's score is 85, JavaScript first checks score >= 90 (false), then checks score >= 80 (true), and immediately outputs "B" without ever evaluating score >= 70. This top-to-bottom evaluation order means the sequence of your conditions matters. Placing the most specific or restrictive conditions first ensures that the correct branch is selected.
SECTION 4
How If/Else Chains Work Under the Hood
Let's look at the exact syntax and mechanics. An if/else chain in JavaScript follows a precise structure. Understanding each piece will help you write chains that are both correct and readable.
Basic if Statement
IF SYNTAX
condition — any expression that evaluates to a truthy or falsy value. { } — curly braces define the code block that runs when the condition is true.
if/else Statement
IF/ELSE SYNTAX
Exactly one of the two blocks will execute. If the condition is true, path A runs. If it's false, path B runs. There is no scenario where both or neither execute.
Full else-if Chain
ELSE-IF CHAIN SYNTAX
JavaScript evaluates cond1 first. If false, it moves to cond2, then cond3. The else block runs only if every condition above it was false. You can use as many else if blocks as needed.
A common mistake is writing conditions in the wrong order. For instance, if you check score >= 70 before score >= 90, a student with a 95 would match the first condition and receive a "C" instead of an "A". Always order your conditions from most restrictive to least restrictive so that the most specific match is found first.
Watch Out: = vs. ==
= is the assignment operator — it sets a variable's value. A double == or triple === is the comparison operator. Writing if (x = 5) instead of if (x === 5) is one of the most common bugs in JavaScript. Use === (strict equality) to avoid type coercion surprises.SECTION 5
Common Patterns & Condition Types
If/else chains become truly powerful when you combine different types of conditions. You'll encounter several recurring patterns in real-world JavaScript. The diagram below classifies the most common comparison and logical operators that appear inside if/else conditions.
The range checking pattern is perhaps the most common use of else-if chains. It works by testing conditions from the highest threshold down to the lowest, so each branch implicitly handles a range. For example, if you've already checked score >= 90 and it was false, you know the score is below 90 when you reach the score >= 80 check. This means you don't need to write score >= 80 && score < 90 — the chain's structure handles the upper bound automatically.
The compound conditions pattern uses && and || to test multiple things at once. For example, a theme park ride might require height >= 48 && age >= 8 — both conditions must be true for the rider to be allowed on.
SECTION 6
Worked Example — Ticket Pricing System
Let's build a real if/else chain step by step. A movie theater charges different prices based on age: children under 5 are free, children 5–12 pay $8, teens 13–17 pay $10, adults 18–64 pay $14, and seniors 65 and above pay $9. We need to write a function that returns the correct price.
Movie Ticket Price Calculator
- 1
Step 1 — Identify the Conditions
We have five age groups, each with a different price. We need to test age ranges from the youngest up or oldest down. Here we'll test from youngest to oldest:age < 5,age <= 12,age <= 17,age <= 64, and everyone else (65+).5 conditions → oneif, threeelse if, oneelse - 2
Step 2 — Write the Function Skeleton
We declare a function namedgetTicketPricethat takes anageparameter and will return a number. We also declare apricevariable withletso we can assign it inside the chain.function getTicketPrice(age) { let price; ... return price; } - 3
Step 3 — Build the If/Else Chain
The first condition checksif (age < 5)and setsprice = 0. The next checkselse if (age <= 12)— we don't needage >= 5 &&because the chain already established the age is 5 or above when the first condition failed. Similarly,else if (age <= 17)handles teens,else if (age <= 64)handles adults, andelsecatches seniors.Complete chain:if (age < 5) { price = 0; } else if (age <= 12) { price = 8; } else if (age <= 17) { price = 10; } else if (age <= 64) { price = 14; } else { price = 9; } - 4
Step 4 — Trace Through with a Test Value
Let's test withage = 15. JavaScript checks:15 < 5→ false.15 <= 12→ false.15 <= 17→ true! JavaScript enters this block, setsprice = 10, and skips everything below.getTicketPrice(15)returns 10 - 5
Step 5 — Verify Edge Cases
Good practice is to test boundary values.getTicketPrice(5)should return 8 (child), and indeed5 < 5is false, but5 <= 12is true. TestinggetTicketPrice(65)should return 9 (senior) —65 <= 64is false, so the else block catches it correctly.Edge cases pass ✓ — boundaries at 5, 13, 18, and 65 all produce the correct price.
SECTION 7
If/Else Chains vs. Other Approaches
If/else chains are not the only way to handle conditional logic in JavaScript. Depending on the situation, other approaches might be cleaner or more efficient. The table below compares if/else chains with two common alternatives: the switch statement and the ternary operator.
| Feature | If/Else Chain | Switch Statement | Ternary Operator |
|---|---|---|---|
| Best for | Range checks, complex conditions with && and || | Matching a single variable against many exact values | Simple true/false decisions in a single expression |
| Readability | Very readable for 2–5 branches; can get long | Clean for many exact-match cases | Compact but confusing when nested |
| Condition type | Any Boolean expression | Strict equality only (===) | Any Boolean expression |
| Can return values? | Must assign to variable or use return | Must assign to variable or use return | Yes — it is an expression itself |
| Common pitfall | Conditions in wrong order | Forgetting the break statement | Nesting ternaries makes code unreadable |
Comparison of JavaScript conditional constructs
WHEN TO USE IF/ELSE CHAINS
SECTION 8
Connection to Advanced Patterns
If/else chains are your entry point into a much larger world of conditional logic. As you progress in programming, you'll discover patterns that build on and sometimes replace simple chains. The table below shows how if/else chains connect to concepts you'll encounter in more advanced courses.
| Concept | If/Else Chain (What You Know) | Advanced Version (What's Next) |
|---|---|---|
| Guard Clauses | Long chain with nested blocks and an else at the end | Return early from a function as soon as an invalid condition is detected, reducing nesting |
| Lookup Objects | Chaining else-if to match exact string/number values | Store key-value pairs in an object and look up the result directly — no chain needed |
| Polymorphism (OOP) | Using if/else to call different functions based on a "type" variable | Define different classes that each implement the same method differently — the correct one is called automatically |
| Pattern Matching | Checking a value against multiple patterns with if/else | Languages like Rust and upcoming JavaScript proposals offer match expressions that handle this more elegantly |
From if/else chains to advanced conditional patterns
Don't worry about mastering these advanced patterns right now. The important thing is that every advanced conditional pattern is rooted in the same if/else logic you're learning in this lesson. Guard clauses are just if statements that return early. Lookup objects are a clever way to avoid long chains. Even polymorphism in object-oriented programming is really just a sophisticated way for the language to pick the right code path — which is exactly what an if/else chain does.
Coming Up Next
SECTION 9
Practice Problems
Test your understanding with these five problems. They start with a simple concept check and build up to a challenge that requires you to think critically about how if/else chains behave.
Question 1: CONCEPTUAL
x is 100, both x > 50 and x > 90 are true. Which branch executes, and why?Show answer
x > 50 is listed before x > 90, the x > 50 branch executes and the x > 90 branch is never checked. This is why you should order conditions from most specific to least specific.Question 2: BASIC CALCULATION
temperature = 72:
if (temperature >= 90) { console.log("Hot"); } else if (temperature >= 70) { console.log("Warm"); } else if (temperature >= 50) { console.log("Cool"); } else { console.log("Cold"); }Show answer
"Warm". JavaScript first checks 72 >= 90, which is false. Then it checks 72 >= 70, which is true. It prints "Warm" and skips the remaining conditions. Even though 72 >= 50 would also be true, JavaScript never evaluates it because a matching branch was already found.Question 3: INTERMEDIATE
category.Show answer
let category; if (bmi >= 30) { category = "Obese"; } else if (bmi >= 25) { category = "Overweight"; } else if (bmi >= 18.5) { category = "Normal"; } else { category = "Underweight"; } We start with the highest threshold (30) and work downward. By the time we reach the bmi >= 18.5 check, we already know the BMI is below 25 (since the previous condition was false). The else catches everything below 18.5.Question 4: APPLIED
getShippingCost(weight, isInternational) using if/else chains that returns the correct cost.Show answer
function getShippingCost(weight, isInternational) { if (isInternational) { if (weight < 1) { return 15; } else if (weight <= 5) { return 25; } else { return 50; } } else { if (weight < 1) { return 5; } else if (weight <= 5) { return 10; } else { return 20; } } } The outer if/else splits on domestic vs. international. Each branch then uses its own if/else chain to handle weight ranges. This demonstrates that if/else chains can be nested inside one another when you need to branch on multiple criteria.Question 5: CRITICAL THINKING
if (score >= 60) { grade = "D"; } else if (score >= 70) { grade = "C"; } else if (score >= 80) { grade = "B"; } else if (score >= 90) { grade = "A"; } else { grade = "F"; } When they test with score = 95, they get "D" instead of "A". Explain the bug, fix the code, and describe a general rule that would prevent this kind of mistake in the future.Show answer
if (score >= 90) { grade = "A"; } else if (score >= 80) { grade = "B"; } else if (score >= 70) { grade = "C"; } else if (score >= 60) { grade = "D"; } else { grade = "F"; } The general rule is: when using range-based conditions in an if/else chain, always test from the most restrictive (highest threshold) to the least restrictive (lowest threshold). This ensures that a value like 95 is caught by the tightest-fitting condition first, rather than being matched by a broad condition early in the chain.SUMMARY
Summary — If/Else Chains in JavaScript
Summary
An if/else chain lets your JavaScript program choose between multiple paths by testing conditions from top to bottom. The chain starts with an if block, can include any number of else if blocks for additional conditions, and optionally ends with an else block that catches everything else. JavaScript executes only the first matching branch and skips all remaining blocks — this is called short-circuit evaluation.
When writing if/else chains, always order conditions from most restrictive to least restrictive to avoid logic bugs. Use comparison operators (===, !==, >, <, >=, <=) for individual tests and logical operators (&&, ||, !) to combine conditions. Always use strict equality (===) instead of loose equality (==) to avoid type coercion surprises. As you advance, you'll learn patterns like guard clauses, switch statements, and lookup objects that build on this foundation.