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.
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.
| 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.
// ── 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");
}{ } 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.
// ── 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.
// ── 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 ☀️"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.
// ── 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.");
}
}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.
if (score >= 60) {
label = "Pass";
} else {
label = "Fail";
}
score >= 60
? "Pass"
: "Fail";
// ── 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 />;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 |
// ── 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 tests if the switch value equals that
label.else.break deliberately to share code between
cases.// ── 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.
Common Patterns & Recipes
These conditional patterns appear constantly in real JavaScript projects. Master them to write clean, predictable, and expressive code.
// ── 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";
}
}if / else if / else chain, how many blocks will
execute?if ([]) { ... } do?5 > 3 ? "yes" : "no"?- The
ifstatement runs a block only when its condition is truthy. Always use curly braces{ }even for single-line bodies to prevent subtle bugs. elseprovides a fallback path that runs when theifcondition is falsy. Exactly one of the two blocks always executes.else ifchains 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, andNaN. Notably,[]and{}are truthy even when empty. - The ternary operator
condition ? a : bis a concise shorthand for simple if/else value assignments. Avoid chaining more than two ternaries — useif/elseinstead for readability. - The switch statement uses strict equality (
===) to match a single value against many fixed cases. Always addbreakunless 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
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.