Conditions with if, else, and else if

Course: JavaScript Beginner

Lesson 8: Conditions with if, else, and else if

Level

Beginner

Estimated Reading Time

10–15 minutes

Goal

By the end of this lesson, the learner will be able to:

  • Write if, else, and else if statements to control which code runs
  • Use the ternary operator for simple true/false decisions
  • Structure conditions clearly so they are easy to read and debug

Frontend Development Context

Conditions are how your code makes decisions. Without them, every user would see the same thing regardless of whether they are logged in or out, whether their cart is full or empty, or whether the data loaded successfully or failed. Every meaningful UI state change — show an error, hide a spinner, display a welcome message — is driven by a condition.

In frontend development, you will write conditions constantly: to guard against missing data before accessing it, to show different content for different user roles, to provide feedback on form validation, and to branch between loading, error, and success states. Writing conditions clearly is as important as writing them correctly.

Explanation

An if statement runs a block of code only when its condition is truthy. The condition goes inside parentheses, and the code to run goes inside curly braces. If the condition is falsy, the block is skipped entirely.

An else clause can follow an if block to provide code that runs when the condition is falsy. Between if and else, you can add any number of else if clauses, each with their own condition. JavaScript evaluates them in order — the first one whose condition is truthy runs, and all the rest are skipped.

The ternary operator (condition ? valueIfTrue : valueIfFalse) is a compact expression form of if/else. It is useful when you need to choose between two values — for example when setting a variable or determining display text. It should not be nested deeply, as that quickly becomes unreadable.

One important habit is to handle the most specific or exceptional cases first, and the most general case last (in else). This makes the logic read naturally — the important guard conditions are at the top, and the default behavior is at the bottom.

When conditions involve multiple values, break them into named variables to make the logic readable. A condition like if (user && user.subscription && user.subscription.plan === "premium" && !user.isBanned) is hard to read — extracting the pieces into named booleans makes it much clearer.

Code Example

This example shows a grading system with multiple branches and a fallback:

function getGradeLabel(score) {
  if (score >= 90) {
    return "A — Excellent";
  } else if (score >= 80) {
    return "B — Good";
  } else if (score >= 70) {
    return "C — Passing";
  } else if (score >= 60) {
    return "D — Needs Improvement";
  } else {
    return "F — Did Not Pass";
  }
}

const studentScore = 84;
const label = getGradeLabel(studentScore);

// Ternary for a simple pass/fail message
const resultText = studentScore >= 60 ? "Passed" : "Failed";

document.querySelector("#grade").textContent = label;
document.querySelector("#result").textContent = resultText;

Code Explanation

The getGradeLabel function uses an if / else if / else chain to map a numeric score to a letter grade label. Each condition is checked in order from highest to lowest. When score is 84, the first condition (>= 90) is false, the second (>= 80) is true, so "B — Good" is returned and the rest of the chain is skipped.

The conditions use >= (greater than or equal), not >. This matters — a score of exactly 80 should get a B, not a C. Writing the boundaries carefully is critical for conditions to produce correct results.

The ternary at the bottom handles the simpler pass/fail label. Because there are only two possible outcomes, a ternary is appropriate here — it is readable in one line. The same logic written as a full if/else would be four extra lines without adding any clarity.

Both results are placed into the DOM at the end, updating the page. The function itself does not touch the DOM — it just takes a number and returns a string. This separation of logic from rendering is a good practice even at the beginner level.

Pattern Highlights

Positive Pattern: Use else if chains when there are three or more distinct outcomes. Start with the most specific condition and end with a general else as the fallback for any case not covered above.

⚠️ Neutral Note: The ternary operator is great for simple two-outcome decisions, but nesting ternaries (a ? b : c ? d : e) is hard to read. Use a full if/else chain when there are more than two outcomes.

Negative Pattern: Omitting curly braces around if blocks may work for single statements, but it is error-prone. Adding a second line inside an indent-only block does not actually belong to the if — always use braces.

Common Mistakes

Mistake 1: Using assignment = instead of comparison === in a condition

A single = assigns a value rather than comparing it. In an if condition, the assigned value is then evaluated as truthy or falsy.

let role = "viewer";

if (role = "admin") { // assigns "admin" to role — always truthy!
  console.log("Is admin"); // always runs, regardless of original role value
}

Use === to compare: if (role === "admin"). This is a silent bug — JavaScript will not warn you.

Mistake 2: Overlapping conditions in the wrong order

When conditions in an else if chain are not ordered correctly, earlier conditions can swallow inputs intended for later ones.

function classify(n) {
  if (n > 0) {
    return "positive";
  } else if (n > 100) { // never reached! n > 100 implies n > 0 already
    return "large positive";
  }
}

Put the most specific conditions first. Here, n > 100 should come before n > 0.

Mistake 3: Forgetting the else for the fallback case

Without an else, the function may return undefined when no condition matches.

function getStatusColor(status) {
  if (status === "success") return "green";
  if (status === "error") return "red";
  // If status is "pending" or anything else — returns undefined
}

const color = getStatusColor("pending");
document.querySelector("#status").style.color = color; // sets color to undefined — broken

Always add an else (or a final default if) to handle unexpected values and prevent your code from silently returning undefined.

Quick Recap

  • if runs a block when the condition is truthy; else if adds additional conditions; else handles everything else
  • Conditions are evaluated in order — the first matching branch runs and the rest are skipped
  • Use the ternary operator for simple two-outcome decisions: condition ? valueA : valueB
  • Always handle the most specific cases first and include a final else to catch unexpected values

Ready to test your understanding? Take the quiz to reinforce what you learned.

© 2026 Ant Skillsv.26.07.07-23:01