Tutorials JavaScript if / else / else if
Ch 16 / 78
Chapter 16 Beginner 8 min read JavaScript

if / else / else if

Conditional statements let your program make decisions and execute different blocks of code based on whether a condition is true or false. The if, else, and else if keywords are the backbone of all program logic — from simple validations to complex branching workflows. Mastering them unlocks the ability to write truly dynamic, intelligent code.

What you'll learn
The if statement — basic conditional execution
else — fallback when the condition is false
else if — multiple branches and conditions
Nested if statements and when to avoid them
Ternary operator — concise one-line conditionals
switch vs if/else — when to use each

Conditional Statement Overview

A conditional statement evaluates a condition (any expression that resolves to true or false) and decides which block of code to run. JavaScript offers several forms, each suited to different situations.

if
Run a block only when a condition is true. The most basic decision.
else
A fallback block that runs only when the if condition is false.
else if
Chain multiple conditions — checked in order, first match wins.
Ternary (?:)
A one-liner shorthand for simple if/else value assignments.
switch
Match a single value against many cases — cleaner than long else-if chains.
Keyword Purpose When to Use
if Execute block when condition is true Always — every conditional starts with if
else Execute block when if condition is false When you need a fallback / default path
else if Test another condition when previous was false 2–5 mutually exclusive conditions
? : Return one of two values based on condition Simple value assignments, JSX, short expressions
switch Match one value against many fixed cases 6+ branches or matching a single variable

The if Statement

The if statement is the simplest conditional form. The code inside its curly braces runs only when the condition evaluates to a truthy value. If the condition is falsy, the block is skipped entirely.

Anatomy of an if statement
if The keyword that starts a conditional block.
(condition) Any expression that evaluates to true or false. Can use comparison and logical operators.
{ ... } The body — one or more statements to execute when condition is truthy. Always use braces, even for single lines.
if (condition)
Block runs only when truthy
age >= 18 runs ✓
age < 18 skipped
score === 100 runs ✓
0 (falsy) skipped
"hello" (truthy) runs ✓
else { }
Runs when if condition is false
if (true) → else skipped
if (false) → else runs ✓
if (0) → else runs ✓
if ("") → else runs ✓
if (null) → else runs ✓
JavaScript — if Statement
// ── Basic if ─────────────────────────────────────────────────
const age = 20;

if (age >= 18) {
console.log("You are an adult."); // runs ✓
}

// ── if with a falsy condition ─────────────────────────────────
const isLoggedIn = false;

if (isLoggedIn) {
console.log("Welcome back!"); // skipped — condition is false
}

// ── if with any truthy value ──────────────────────────────────
const username = "Alice";

if (username) { // non-empty string is truthy
console.log(`Hello, ${username}`); // runs ✓
}

// ── Always use curly braces ───────────────────────────────────
if (age > 0) console.log("positive"); // ⚠ works, but risky — always add {}
if (age > 0) { // ✓ safer and clearer
console.log("positive");
}
Best Practice
Always use curly braces { } around your if body, even for single-line statements. Omitting them is a common source of bugs when a second line is added later and accidentally falls outside the block.

if / else

Adding an else clause gives your condition a fallback path. When the if condition is falsy, the else block runs instead. Exactly one of the two blocks will always execute — they are mutually exclusive.

JavaScript — if / else
// ── Basic if/else ─────────────────────────────────────────────
const score = 55;

if (score >= 60) {
console.log("Pass ✓"); // skipped — 55 < 60
} else {
console.log("Fail ✗"); // runs ✓
}

// ── Even-or-odd check ─────────────────────────────────────────
const num = 7;

if (num % 2 === 0) {
console.log("Even");
} else {
console.log("Odd"); // runs ✓ (7 % 2 === 1)
}

// ── Login guard ───────────────────────────────────────────────
function greet(user) {
if (user) {
console.log(`Welcome, ${user}!`);
} else {
console.log("Please log in.");
}
}

greet("Alice"); // "Welcome, Alice!"
greet(null); // "Please log in."

else if — Multiple Branches

When you need to test more than two possibilities, chain else if blocks between your if and else. JavaScript evaluates each condition in order from top to bottom — the first one that is truthy wins, and the rest are skipped.

JavaScript — else if Chains
// ── Grade calculator ─────────────────────────────────────────
const score = 74;

if (score >= 90) {
console.log("A — Excellent"); // skipped
} else if (score >= 80) {
console.log("B — Good"); // skipped
} else if (score >= 70) {
console.log("C — Satisfactory"); // runs ✓ (74 >= 70)
} else if (score >= 60) {
console.log("D — Passing"); // skipped (already matched above)
} else {
console.log("F — Fail"); // skipped
}

// ── Time-of-day greeting ─────────────────────────────────────
const hour = 14; // 2 PM
let greeting;

if (hour < 12) {
greeting = "Good morning 🌅";
} else if (hour < 18) {
greeting = "Good afternoon ☀️"; // runs ✓ (12 <= 14 < 18)
} else {
greeting = "Good evening 🌙";
}

console.log(greeting); // "Good afternoon ☀️"
Order Matters
JavaScript checks conditions from top to bottom and stops at the first match. If you put a broader condition before a narrower one — like score >= 60 before score >= 90 — the broader one will always match first and the narrower ones will never run. Always put the most specific condition first.

Nested if Statements

You can place an if statement inside another if block — this is called nesting. It lets you check a secondary condition only after the primary one passes. However, deep nesting quickly becomes hard to read — keep it to 2 levels max, and consider early returns or logical operators as cleaner alternatives.

JavaScript — Nested vs Flat Conditions
// ── Nested if (works but can get messy) ──────────────────────
function checkAccess(isLoggedIn, role) {
if (isLoggedIn) {
if (role === "admin") {
console.log("Admin panel access granted.");
} else {
console.log("User access granted.");
}
} else {
console.log("Please log in first.");
}
}

// ── Flattened with && (cleaner for simple cases) ─────────────
function checkAccessFlat(isLoggedIn, role) {
if (!isLoggedIn) {
console.log("Please log in first.");
return; // early return — exit immediately
}

if (role === "admin") {
console.log("Admin panel access granted.");
} else {
console.log("User access granted.");
}
}

// ── Using && to combine (ultra-flat) ─────────────────────────
function checkAccessAnd(isLoggedIn, role) {
if (isLoggedIn && role === "admin") {
console.log("Admin panel access granted.");
} else if (isLoggedIn) {
console.log("User access granted.");
} else {
console.log("Please log in first.");
}
}
Avoid Deep Nesting
More than 2 levels of nested if statements is a code smell. Use early returns (guard clauses) to handle edge cases first and flatten your logic. This makes code easier to read, test, and maintain.

Ternary Operator ( ? : )

The ternary operator is a compact one-line shorthand for a simple if / else. It takes three operands: a condition, a value if true, and a value if false. It's ideal for simple value assignments and JSX expressions — but avoid it when the logic becomes complex.

Anatomy of the ternary operator
condition Any expression that evaluates to true or false.
? valueA Expression returned/executed when condition is truthy.
: valueB Expression returned/executed when condition is falsy.
✗ Verbose — if / else
let label;
if (score >= 60) {
  label = "Pass";
} else {
  label = "Fail";
}
✓ Concise — Ternary
const label =
  score >= 60
    ? "Pass"
    : "Fail";
JavaScript — Ternary Operator
// ── Basic ternary ─────────────────────────────────────────────
const age = 20;
const status = age >= 18 ? "adult" : "minor";
console.log(status); // "adult"

// ── In template literals ──────────────────────────────────────
const items = 3;
console.log(`You have ${items} item${items !== 1 ? "s" : ""}`);
// "You have 3 items"

// ── Default value ─────────────────────────────────────────────
const username = null;
const display = username ? username : "Guest";
// Even better: const display = username ?? "Guest";

// ── Chained ternary (use sparingly) ───────────────────────────
const score = 74;
const grade = score >= 90 ? "A"
: score >= 80 ? "B"
: score >= 70 ? "C"
: score >= 60 ? "D"
: "F"; // ⚠ use if/else chain for clarity when this gets long

// ── Ternary for JSX (React) ───────────────────────────────────
// const button = isLoggedIn ? <LogoutBtn /> : <LoginBtn />;
When to use ternary
Use the ternary for simple, readable one-liners — especially for picking a value. Avoid chaining more than two ternaries or putting side effects (like console.log) inside them. If the expression needs two lines to be readable, use if / else instead.

Truthy & Falsy in Conditions

JavaScript if statements don't require a strict true or false — they evaluate any value for its truthiness. There are exactly 6 falsy values in JavaScript. Everything else is truthy — including empty arrays and empty objects.

Value Type in if() it is…
false Boolean falsy
0 Number falsy
-0 Number falsy
0n BigInt falsy
"" String (empty) falsy
null Null falsy
undefined Undefined falsy
NaN Number falsy
"hello" String (non-empty) truthy
42 Number (non-zero) truthy
[] Array (empty) truthy
{} Object (empty) truthy
JavaScript — Truthy & Falsy in if Statements
// ── Falsy values — if block is SKIPPED ───────────────────────
if (false) { console.log("runs"); } // skipped
if (0) { console.log("runs"); } // skipped
if ("") { console.log("runs"); } // skipped
if (null) { console.log("runs"); } // skipped
if (undefined){ console.log("runs"); } // skipped
if (NaN) { console.log("runs"); } // skipped

// ── Truthy values — if block RUNS ────────────────────────────
if (true) { console.log("runs"); } // ✓ runs
if (1) { console.log("runs"); } // ✓ runs
if ("hello") { console.log("runs"); } // ✓ runs
if ([]) { console.log("runs"); } // ✓ runs — empty array is truthy!
if ({}) { console.log("runs"); } // ✓ runs — empty object is truthy!

// ── Common guard pattern ──────────────────────────────────────
const items = [];
if (items.length > 0) { // ✓ correct: check .length, not [] directly
console.log("Has items");
} else {
console.log("Empty list"); // runs — length is 0
}

switch Statement

The switch statement is an alternative to long else if chains when you're comparing a single variable against many fixed values. It uses strict equality (===) to match cases. Don't forget break — without it, execution falls through into the next case.

case
Match a Value
Each case tests if the switch value equals that label.
case "admin": ...
break
Stop Execution
Exits the switch after a matching case. Omitting it causes fall-through.
break;
default
Fallback
Runs when no case matches — equivalent to else.
default: ...
fall-through
Intentional Grouping
Omit break deliberately to share code between cases.
case "a": case "b": ...
JavaScript — switch Statement
// ── Basic switch ─────────────────────────────────────────────
const day = "Monday";

switch (day) {
case "Monday":
console.log("Start of the work week 💼");
break;
case "Friday":
console.log("Last day — almost weekend! 🎉");
break;
case "Saturday":
case "Sunday": // fall-through — both share this block
console.log("Weekend! Rest up 🌴");
break;
default:
console.log("Midweek — keep going 💪");
}

// ── switch uses === (strict) ──────────────────────────────────
switch (1) {
case 1: console.log("number 1"); break; // ✓ matches
case "1": console.log("string 1"); break; // ✗ different type
}

// ── Return from switch inside a function ─────────────────────
function getDiscount(tier) {
switch (tier) {
case "gold": return 0.20;
case "silver": return 0.10;
case "bronze": return 0.05;
default: return 0;
}
}

Try It — Live Editor

Experiment with JavaScript conditional statements below. Change values, test different branches, and observe which code paths execute — all without leaving this page.

Live Editor
✎ Editor
👁 Preview

Common Patterns & Recipes

These conditional patterns appear constantly in real JavaScript projects. Master them to write clean, predictable, and expressive code.

JavaScript — Conditional Recipes
// ── Early return (guard clause) ──────────────────────────────
function processOrder(order) {
if (!order) return; // guard: exit early if no order
if (!order.items.length) return; // guard: empty cart
if (order.total < 0) return; // guard: invalid total

processPayment(order); // only runs when all checks pass
}

// ── Conditional rendering ─────────────────────────────────────
const isAdmin = true;
const panel = isAdmin ? "<AdminPanel />" : "<UserPanel />";

// ── Range check ──────────────────────────────────────────────
const score = 85;
const isPassing = score >= 60 && score <= 100;

// ── Feature flag ─────────────────────────────────────────────
const DARK_MODE_ENABLED = true;
if (DARK_MODE_ENABLED) applyDarkTheme();

// ── Null check before accessing property ─────────────────────
if (user && user.profile && user.profile.avatar) {
showAvatar(user.profile.avatar);
}
// Modern equivalent using optional chaining:
if (user?.profile?.avatar) { showAvatar(user.profile.avatar); }

// ── Switch with return (no break needed) ─────────────────────
function httpMessage(code) {
switch (code) {
case 200: return "OK";
case 404: return "Not Found";
case 500: return "Server Error";
default: return "Unknown";
}
}
⚡
Free Resource
Download our JavaScript Cheat Sheet
All conditionals, control flow patterns & decision trees — one printable page.
Get Sheet
Quick Check
In an if / else if / else chain, how many blocks will execute?
Quick Check
What does if ([]) { ... } do?
Quick Check
What is the result of 5 > 3 ? "yes" : "no"?
Chapter Summary
  • The if statement runs a block only when its condition is truthy. Always use curly braces { } even for single-line bodies to prevent subtle bugs.
  • else provides a fallback path that runs when the if condition is falsy. Exactly one of the two blocks always executes.
  • else if chains let you test multiple conditions in order. JavaScript stops at the first match — order matters, so put the most specific conditions first.
  • JavaScript evaluates any value for truthiness. The 6 falsy values are: false, 0, "", null, undefined, and NaN. Notably, [] and {} are truthy even when empty.
  • The ternary operator condition ? a : b is a concise shorthand for simple if/else value assignments. Avoid chaining more than two ternaries — use if/else instead for readability.
  • The switch statement uses strict equality (===) to match a single value against many fixed cases. Always add break unless intentionally using fall-through.
  • Guard clauses (early returns) flatten deeply nested conditionals into cleaner, more readable code by handling edge cases first and returning immediately.

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel