JavaScript • Control Flow

If/Else Chains — Write if/else and else-if chains

Teach your programs to make decisions by choosing different paths based on conditions.

JavaScript emblem with code brackets, braces, and a code file.
Inside this lesson 10 sections 5 questions 7 figures

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

George Boole published The Mathematical Analysis of Logic, introducing a system of algebra based on true/false values. This became the mathematical foundation for all conditional logic in computing.

1946 • ENIAC and Conditional Branching

The ENIAC computer, one of the first general-purpose electronic computers, could execute conditional branches — choosing between different instruction paths based on computed results.

1957 • Fortran's IF Statement

IBM's Fortran language introduced one of the first high-level IF statements, allowing programmers to write conditional logic in something closer to human language rather than raw machine code.

1972 • C Language Formalizes if/else

Dennis Ritchie's C programming language established the if/else if/else syntax pattern that JavaScript and many other modern languages still use today.

1995 • JavaScript Adopts if/else

Brendan Eich created JavaScript in just ten days. He borrowed the if/else chain syntax directly from C and Java, ensuring that web pages could make dynamic decisions right in the browser.

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.

1

The if Block

The 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.
2

The else Block

The 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.
3

The else if Block

The 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.
4

Short-Circuit Evaluation

JavaScript evaluates conditions from top to bottom and stops at the first true condition. Once a matching branch is found, all remaining else if and else blocks are skipped entirely.
5

Boolean Coercion

JavaScript automatically converts the condition to a Boolean. Values like 0, "", null, and undefined are treated as falsy; most other values are truthy.
✦

KEY TAKEAWAY

Think of an if/else chain like a hallway with locked doors. You walk down the hallway and try each door in order. The first door that opens is the one you walk through — you don't bother checking the rest. If none of the doors open, the 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.

If / Else If / Else Chain — Grade Calculatorscore >= 90?TRUE"A"FALSEscore >= 80?TRUE"B"FALSEscore >= 70?TRUE"C"FALSEelse → "F"Diamonds = conditions · Rectangles = code blocks (only one executes)
Each diamond represents a condition that JavaScript tests. The program follows the TRUE arrow on the first condition that passes and skips all remaining checks. The else block at the bottom catches anything that didn't match an earlier condition.

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

if(condition)//codetorunwhenconditionistrueif (condition) { // code to run when condition is true }

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

if(condition)//pathAelse//pathBif (condition) { // path A } else { // path B }

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

if(cond1)Aelseif(cond2)Belseif(cond3)CelseDif (cond1) { A } else if (cond2) { B } else if (cond3) { C } else { D }

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. ==

A single = 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.

Operators Used in If/Else ConditionsComparison Operators===Strict equal!==Strict not equal>Greater than<Less than>=Greater than or equal<=Less than or equalLogical Operators&&AND — both must be true||OR — at least one must be true!NOT — flips true to falseCommon If/Else Chain PatternsRange Checkingscore >= 90, >= 80...Category Matchingtype === "admin"Compound Conditionsage >= 16 && hasPermitExistence Checkingif (user) { ... }Negation Patternsif (!isLoggedIn) { ... }
This reference chart groups the operators and patterns you'll use most often inside if/else conditions. Comparison operators compare two values, logical operators combine multiple conditions, and the common patterns show how they appear in real code.

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. 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 → one if, three else if, one else
  2. 2

    Step 2 — Write the Function Skeleton

    We declare a function named getTicketPrice that takes an age parameter and will return a number. We also declare a price variable with let so we can assign it inside the chain.
    function getTicketPrice(age) { let price; ... return price; }
  3. 3

    Step 3 — Build the If/Else Chain

    The first condition checks if (age < 5) and sets price = 0. The next checks else if (age <= 12) — we don't need age >= 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, and else catches 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. 4

    Step 4 — Trace Through with a Test Value

    Let's test with age = 15. JavaScript checks: 15 < 5 → false. 15 <= 12 → false. 15 <= 17 → true! JavaScript enters this block, sets price = 10, and skips everything below.
    getTicketPrice(15) returns 10
  5. 5

    Step 5 — Verify Edge Cases

    Good practice is to test boundary values. getTicketPrice(5) should return 8 (child), and indeed 5 < 5 is false, but 5 <= 12 is true. Testing getTicketPrice(65) should return 9 (senior) — 65 <= 64 is 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.

FeatureIf/Else ChainSwitch StatementTernary Operator
Best forRange checks, complex conditions with && and ||Matching a single variable against many exact valuesSimple true/false decisions in a single expression
ReadabilityVery readable for 2–5 branches; can get longClean for many exact-match casesCompact but confusing when nested
Condition typeAny Boolean expressionStrict equality only (===)Any Boolean expression
Can return values?Must assign to variable or use returnMust assign to variable or use returnYes — it is an expression itself
Common pitfallConditions in wrong orderForgetting the break statementNesting ternaries makes code unreadable

Comparison of JavaScript conditional constructs

✦

WHEN TO USE IF/ELSE CHAINS

Reach for an if/else chain whenever your conditions involve ranges (like score thresholds), compound logic (combining conditions with && or ||), or when you need to execute multiple statements in each branch. For simple true/false toggles, a ternary is more concise. For matching one variable against many exact values (like days of the week), a switch statement is cleaner.

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.

ConceptIf/Else Chain (What You Know)Advanced Version (What's Next)
Guard ClausesLong chain with nested blocks and an else at the endReturn early from a function as soon as an invalid condition is detected, reducing nesting
Lookup ObjectsChaining else-if to match exact string/number valuesStore 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" variableDefine different classes that each implement the same method differently — the correct one is called automatically
Pattern MatchingChecking a value against multiple patterns with if/elseLanguages 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

Once you're comfortable with if/else chains, the natural next step is learning switch statements for cleaner exact-match logic, and then loops (for, while) to repeat decisions across many values. Together, these three constructs — if/else, switch, and loops — form the backbone of all control flow in JavaScript.

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

In an if/else chain, what happens if more than one condition is true? For example, if x is 100, both x > 50 and x > 90 are true. Which branch executes, and why?
Show answer
JavaScript evaluates conditions from top to bottom and executes only the first branch whose condition is true. Once that branch runs, all remaining else-if and else blocks are skipped entirely. So if 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

Trace through this code and determine the output when 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
The output is "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

Write an if/else chain that classifies a BMI value into four categories: Underweight (below 18.5), Normal (18.5 to 24.9), Overweight (25.0 to 29.9), and Obese (30.0 and above). Store the category as a string in a variable called category.
Show answer
Here is one correct solution: 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

A shipping company calculates cost based on weight and destination. For domestic packages: under 1 lb costs $5, 1–5 lbs costs $10, over 5 lbs costs $20. For international packages: under 1 lb costs $15, 1–5 lbs costs $25, over 5 lbs costs $50. Write a function getShippingCost(weight, isInternational) using if/else chains that returns the correct cost.
Show answer
This problem requires nested if/else chains — one outer chain for the destination, and inner chains for weight: 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

A student writes this code to assign letter grades: 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
The bug is that the conditions are ordered from least restrictive to most restrictive. Since 95 is greater than or equal to 60, the very first condition matches and JavaScript assigns "D" without ever checking the other conditions. The fix is to reverse the order: 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.

Varsity Tutors • JavaScript • If/Else Chains — Write if/else and else-if chains