JavaScript if, else if and else Statements: Conditions with Examples

Programs need to make decisions: retry when a request fails, show an error when a field is empty, mark a test as passed or failed. The if statement is how JavaScript decides which code to run. In this lesson you will learn if, else and else if, combine conditions safely, avoid deep nesting with guard clauses, and replace long if chains with lookup objects.

Advertisement

📖 What You’ll Learn: the if statement, if…else, else if chains and their order, conditions with comparison and logical operators, truthy checks, nested if statements, guard clauses and early returns, the ternary alternative, lookup objects, and common mistakes such as = instead of ===.


🚦 The if Statement

Definition: an if statement runs a block of code only when its condition is truthy. The condition goes in parentheses and the code in curly braces.

📄 Syntax

if (condition) {
  // runs only when condition is truthy
}

📄 if.js

const statusCode = 500;

if (statusCode >= 500) {
  console.log("Server error: retry the request");
}

console.log("Check finished");   // always runs

⌨️ Terminal

node if.js

🖥️ Output

Server error: retry the request
Check finished

The condition can be any expression. It is converted to a boolean using the truthy/falsy rules from the Truthy, Falsy and Equality lesson.

💡 Tip: JavaScript allows if (x) doSomething(); without braces for a single statement. Always use braces anyway: adding a second line later without braces is a classic bug, because only the first line belongs to the if.


↔️ if…else

else adds a block that runs when the condition is falsy. Exactly one of the two blocks runs.

📄 if-else.js

function checkLogin(password) {
  if (password.length >= 8) {
    console.log("Password accepted");
  } else {
    console.log(`Password too short: ${password.length} characters`);
  }
}

checkLogin("secret123");
checkLogin("abc");

⌨️ Terminal

node if-else.js

🖥️ Output

Password accepted
Password too short: 3 characters

🪜 else if Chains

Use else if to test several conditions in order. JavaScript runs the first block whose condition is truthy and skips all the others.

📄 else-if.js

function grade(score) {
  if (score >= 90) {
    return "A";
  } else if (score >= 75) {
    return "B";
  } else if (score >= 60) {
    return "C";
  } else {
    return "F";
  }
}

for (const s of [95, 82, 60, 41]) {
  console.log(s, "->", grade(s));
}

⌨️ Terminal

node else-if.js

🖥️ Output

95 -> A
82 -> B
60 -> C
41 -> F

⚠️ Watch out: Order matters. If the first condition were score >= 60, a score of 95 would match it first and get a C. Put the most specific (or highest) conditions first.

📄 wrong-order.js

function gradeWrongOrder(score) {
  if (score >= 60) return "C";      // matches 95 before the A check
  else if (score >= 90) return "A";
  return "F";
}
console.log(gradeWrongOrder(95));

⌨️ Terminal

node wrong-order.js

🖥️ Output

C

Advertisement

🔗 Combining Conditions with &&, || and !

📄 combined.js

function canCheckout(user, cart) {
  if (user.isLoggedIn && cart.items > 0 && !cart.hasErrors) {
    return "Checkout allowed";
  } else if (!user.isLoggedIn) {
    return "Please log in";
  } else if (cart.items === 0) {
    return "Cart is empty";
  } else {
    return "Fix cart errors first";
  }
}

console.log(canCheckout({ isLoggedIn: true }, { items: 2, hasErrors: false }));
console.log(canCheckout({ isLoggedIn: false }, { items: 2, hasErrors: false }));
console.log(canCheckout({ isLoggedIn: true }, { items: 0, hasErrors: false }));
console.log(canCheckout({ isLoggedIn: true }, { items: 1, hasErrors: true }));

⌨️ Terminal

node combined.js

🖥️ Output

Checkout allowed
Please log in
Cart is empty
Fix cart errors first
  • &&: all parts must be truthy.
  • ||: at least one part must be truthy, for example if (role === "admin" || role === "owner").
  • !: negates a condition. Prefer positive names (isValid) so you rarely need double negatives.

When you compare one value with many options, includes is shorter than a long || chain:

📄 includes.js

const role = "editor";

if (role === "admin" || role === "owner" || role === "editor") {
  console.log("can edit (|| chain)");
}
if (["admin", "owner", "editor"].includes(role)) {
  console.log("can edit (includes)");
}

⌨️ Terminal

node includes.js

🖥️ Output

can edit (|| chain)
can edit (includes)

🪆 Nested if and Guard Clauses

An if can contain another if. A little nesting is fine, but deep nesting is hard to read:

📄 nested.js

function processOrder(order) {
  if (order) {
    if (order.items.length > 0) {
      if (order.paid) {
        return `Shipping order ${order.id}`;
      } else {
        return "Waiting for payment";
      }
    } else {
      return "Order has no items";
    }
  } else {
    return "No order";
  }
}
console.log(processOrder({ id: 7, items: ["pen"], paid: true }));

⌨️ Terminal

node nested.js

🖥️ Output

Shipping order 7

Definition: a guard clause checks for an invalid case at the start of a function and returns early. The remaining code then handles only the normal case, with no nesting:

📄 guard.js

function processOrder(order) {
  if (!order) return "No order";
  if (order.items.length === 0) return "Order has no items";
  if (!order.paid) return "Waiting for payment";

  return `Shipping order ${order.id}`;
}

console.log(processOrder(null));
console.log(processOrder({ id: 8, items: [], paid: true }));
console.log(processOrder({ id: 9, items: ["lamp"], paid: false }));
console.log(processOrder({ id: 10, items: ["lamp"], paid: true }));

⌨️ Terminal

node guard.js

🖥️ Output

No order
Order has no items
Waiting for payment
Shipping order 10

💡 Tip: Guard clauses are the most useful refactoring for beginners. Test helpers, page objects and API clients written this way are much easier to read in a code review.


Advertisement

⚡ Shorter Alternatives: Ternary and Lookup Objects

When an if...else only chooses between two values, the ternary operator is shorter:

📄 ternary.js

const passed = 18, total = 20;

let verdict;
if (passed === total) {
  verdict = "PASS";
} else {
  verdict = "FAIL";
}
console.log(verdict);

const verdict2 = passed === total ? "PASS" : "FAIL";   // same result, one line
console.log(verdict2);

⌨️ Terminal

node ternary.js

🖥️ Output

FAIL
FAIL

When an else if chain maps fixed keys to values, a lookup object is clearer and easier to extend:

📄 lookup.js

const statusText = {
  200: "OK",
  201: "Created",
  400: "Bad Request",
  401: "Unauthorized",
  404: "Not Found",
  500: "Server Error",
};

for (const code of [200, 404, 418]) {
  console.log(code, statusText[code] ?? "Unknown status");
}

⌨️ Terminal

node lookup.js

🖥️ Output

200 OK
404 Not Found
418 Unknown status

⚠️ Common Mistakes

Using = instead of ===

A single = assigns a value, and the assigned value is then used as the condition. This compiles but is almost always a bug:

📄 assign-bug.js

let env = "qa";

if (env = "prod") {           // bug: assigns "prod", which is truthy
  console.log("Running against PRODUCTION!");
}
console.log("env is now:", env);

⌨️ Terminal

node assign-bug.js

🖥️ Output

Running against PRODUCTION!
env is now: prod

Fix: use ===. ESLint’s no-cond-assign rule reports this mistake.

Comparing a range incorrectly

📄 range-bug.js

const age = 40;
console.log(18 < age < 30);            // (18 < 40) is true, then true < 30 -> 1 < 30
console.log(age > 18 && age < 30);     // correct

⌨️ Terminal

node range-bug.js

🖥️ Output

true
false

JavaScript evaluates 18 < age < 30 left to right: the first comparison becomes true, which converts to 1, and 1 < 30 is true. Always combine two comparisons with &&.

A semicolon after the condition

if (isAdmin); { deleteUser(); } runs deleteUser() every time, because the ; ends the if with an empty statement and the block that follows is just a block. Prettier and ESLint catch this.


🧪 Tester Scenario: Classify Test Results

This function turns raw test results into a readable status, the kind of logic used in custom reporters and CI summaries:

📄 classify.js

function classify(result) {
  if (result.skipped) return "⏭️  SKIPPED";
  if (result.error) return `❌ ERROR (${result.error})`;

  const { passed, total, durationMs } = result;
  if (passed === total && durationMs > 60_000) {
    return "⚠️  PASSED BUT SLOW";
  } else if (passed === total) {
    return "✅ PASSED";
  } else if (passed >= total * 0.9) {
    return `🟡 MOSTLY PASSED (${total - passed} failed)`;
  } else {
    return `❌ FAILED (${total - passed} failed)`;
  }
}

const runs = [
  { name: "smoke", passed: 12, total: 12, durationMs: 41_000 },
  { name: "regression", passed: 188, total: 200, durationMs: 540_000 },
  { name: "checkout", passed: 20, total: 20, durationMs: 95_000 },
  { name: "payments", passed: 3, total: 10, durationMs: 30_000 },
  { name: "legacy", skipped: true },
  { name: "api", error: "ECONNREFUSED" },
];

for (const run of runs) {
  console.log(run.name.padEnd(11), classify(run));
}

⌨️ Terminal

node classify.js

🖥️ Output

smoke       ✅ PASSED
regression  🟡 MOSTLY PASSED (12 failed)
checkout    ⚠️  PASSED BUT SLOW
payments    ❌ FAILED (7 failed)
legacy      ⏭️  SKIPPED
api         ❌ ERROR (ECONNREFUSED)
  • Guard clauses handle “skipped” and “error” first, so the rest only deals with real results.
  • The slow-but-passing check comes before the plain “passed” check, because the more specific condition must win.
  • const { passed, total, durationMs } = result; is destructuring, a shortcut covered in Module 6.

Advertisement

📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Write checkAge(age) that prints Minor under 18, Adult from 18 to 59 and Senior from 60. Test it with 15, 18, 59 and 60.

Show answer

📄 practice1.js

function checkAge(age) {
  if (age < 18) {
    console.log(age, "Minor");
  } else if (age < 60) {
    console.log(age, "Adult");
  } else {
    console.log(age, "Senior");
  }
}

[15, 18, 59, 60].forEach(checkAge);

🖥️ Output

15 Minor
18 Adult
59 Adult
60 Senior

Test the boundary values (18, 59, 60) as well as typical values; boundaries are where off-by-one bugs hide.

Q2. Print whether a year is a leap year: divisible by 4, except years divisible by 100, unless also divisible by 400. Test 2024, 1900, 2000 and 2026.

Show answer

📄 practice2.js

function isLeap(year) {
  if (year % 400 === 0) return true;
  if (year % 100 === 0) return false;
  return year % 4 === 0;
}

for (const y of [2024, 1900, 2000, 2026]) {
  console.log(y, isLeap(y) ? "leap" : "not leap");
}

🖥️ Output

2024 leap
1900 not leap
2000 leap
2026 not leap

Q3. Rewrite this nested code with guard clauses.

function login(user) {
  if (user) {
    if (user.active) {
      return "Welcome " + user.name;
    } else {
      return "Account disabled";
    }
  } else {
    return "Unknown user";
  }
}
Show answer

📄 practice3.js

function login(user) {
  if (!user) return "Unknown user";
  if (!user.active) return "Account disabled";
  return `Welcome ${user.name}`;
}

console.log(login(null));
console.log(login({ name: "Asha", active: false }));
console.log(login({ name: "Asha", active: true }));

🖥️ Output

Unknown user
Account disabled
Welcome Asha

Q4. Validate a password: at least 8 characters, contains a digit, and is not equal to "password1". Print the first rule that fails, or Valid.

Show answer

📄 practice4.js

function validate(pw) {
  if (pw.length < 8) return "Too short";
  if (!/\d/.test(pw)) return "Needs a digit";
  if (pw.toLowerCase() === "password1") return "Too common";
  return "Valid";
}

for (const pw of ["abc1", "abcdefgh", "Password1", "qaTester7"]) {
  console.log(pw.padEnd(10), validate(pw));
}

🖥️ Output

abc1       Too short
abcdefgh   Needs a digit
Password1  Too common
qaTester7  Valid

Q5. Replace this else if chain with a lookup object and a default value.

if (browser === "chromium") engine = "Blink";
else if (browser === "firefox") engine = "Gecko";
else if (browser === "webkit") engine = "WebKit";
else engine = "unknown";
Show answer

📄 practice5.js

const ENGINES = { chromium: "Blink", firefox: "Gecko", webkit: "WebKit" };

for (const browser of ["firefox", "webkit", "opera"]) {
  const engine = ENGINES[browser] ?? "unknown";
  console.log(browser, "->", engine);
}

🖥️ Output

firefox -> Gecko
webkit -> WebKit
opera -> unknown

Q6. Find and fix the bug: the code always prints Admin area.

let role = "tester";
if (role = "admin") {
  console.log("Admin area");
} else {
  console.log("Tester area");
}
Show answer

A single = assigns "admin" to role, and the non-empty string is truthy. Use ===:

📄 practice6.js

let role = "tester";
if (role === "admin") {
  console.log("Admin area");
} else {
  console.log("Tester area");
}

🖥️ Output

Tester area

🧠 MCQ Quiz: if, else if, else

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. When does the block of if (value) { ... } run?
  2. In an if / else if / else chain, how many blocks run?
  3. What is printed?
    const n = 95;
    if (n >= 60) console.log("C");
    else if (n >= 90) console.log("A");
  4. What does if (x = 5) do?
  5. What is 3 < 2 < 1?
  6. What is a guard clause?
  7. Which is the clearest way to check whether role is “admin”, “owner” or “editor”?
  8. Why should you always use braces with if?
  9. What runs here?
    if (false); {
      console.log("hi");
    }
  10. When is a lookup object better than an else if chain?

💼 Interview Questions and Answers

Q1. How do if/else and the ternary operator differ?

if/else is a statement: it chooses which block of code to run and can contain any number of statements. The ternary is an expression: it chooses between two values and can be used inside other expressions (assignments, template literals, return statements). Use the ternary for simple value choices and if/else for logic and side effects.

Q2. What are guard clauses and why are they useful?

Guard clauses are checks at the top of a function that return (or throw) early for invalid or special cases. They remove nesting, keep the main path at the lowest indentation level, and make each rule easy to see. In test helpers they produce clear error messages early, for example if (!baseURL) throw new Error("BASE_URL is not set").

Q3. Explain the output of this code.

📄 explain.js

const items = [];
if (items) console.log("has items?");
if (items.length) console.log("really has items");
if ("0") console.log("string zero is truthy");

⌨️ Terminal

node explain.js

🖥️ Output

has items?
string zero is truthy

An empty array is an object, so it is truthy and the first message prints. items.length is 0 (falsy), so the second does not. The string "0" is non-empty and therefore truthy.

Q4. How would you test a function with many if/else branches?

Write at least one test per branch (branch coverage), plus boundary values for each comparison: for score >= 90 test 89, 90 and 91. Include invalid inputs that guard clauses should reject (null, empty arrays, negative numbers). Table-driven tests, an array of input/expected pairs in a loop, keep this compact; Playwright and Jest both support this pattern.

Q5. How can you avoid a long if/else if chain?

  • A lookup object or Map for exact key-to-value mappings.
  • A switch statement for many exact matches with different code (next lesson).
  • Guard clauses for validation rules.
  • Polymorphism (different classes with the same method) for behaviour that varies by type, covered in the OOP module.

Advertisement

❓ Frequently Asked Questions

🤔 Can I write if without curly braces?

Yes, for a single statement, but it is risky because a second line added later would run unconditionally. Most style guides require braces.

🤔 Is there an elseif keyword in JavaScript?

No. JavaScript uses two words, else if. Writing elseif is a syntax error.

🤔 How many else if blocks can I use?

As many as you need, but more than three or four usually means a lookup object, a switch or guard clauses would be clearer.

🤔 What is the difference between if (x) and if (x !== undefined)?

if (x) is false for every falsy value, including 0, “” and false. if (x !== undefined) is true for those values. Use the explicit check when 0 or “” are valid.


🏁 Summary

  • if runs a block when its condition is truthy; else runs when it is not.
  • else if chains test conditions in order and run only the first match, so put specific conditions first.
  • Combine conditions with &&, || and !; use includes for “one of many values”.
  • Guard clauses with early returns replace deep nesting; ternaries and lookup objects replace simple chains.
  • Watch for = instead of ===, chained range comparisons and a stray semicolon after the condition.

Next, continue with Lesson 14: switch Statement. For extra practice, solve the JavaScript if-else practice programs.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in