Conditional Statements in JavaScript
Introduction
Conditional statements run different code paths based on boolean conditions. if, else if, and else are the foundation of validation, permissions, and game logic. This chapter builds on operators and prepares you for switch and loops.
Prerequisites
if Statement
// Simple branch
const temperature = 32;
if (temperature > 30) {
console.log("Hot day");
}if / else
// Two-way branch
const age = 16;
if (age >= 18) {
console.log("Adult ticket");
} else {
console.log("Minor ticket");
}else if Chains
// Multiple branches (first match wins)
const score = 84;
if (score >= 90) {
console.log("A");
} else if (score >= 80) {
console.log("B");
} else if (score >= 70) {
console.log("C");
} else {
console.log("Needs improvement");
}Order matters—put most specific or highest thresholds first when ranges overlap.
Conditions with Logical Operators
// Combine checks
const hasId = true;
const age = 20;
const canEnter = hasId && age >= 18;
if (canEnter) {
console.log("Welcome");
} else {
console.log("Denied");
}Nested if
Use nesting sparingly—early returns or flat else if chains often read better:
// Nested example (acceptable for small cases)
const role = "editor";
const isActive = true;
if (isActive) {
if (role === "admin") {
console.log("Full access");
} else {
console.log("Limited access");
}
}Ternary vs if
Ternary for simple value selection; if for side effects (logging, multiple statements):
// Ternary for assignment
const stock = 3;
const status = stock > 0 ? "in stock" : "sold out";
// if for multiple actions
if (stock === 0) {
console.log("Notify warehouse");
console.log("Show waitlist UI");
}Truthy Conditions (Careful)
// Explicit check when 0 is valid
const discountPercent = 0;
if (discountPercent) {
console.log("Has discount");
} else {
console.log("No discount flag");
}Prefer discountPercent > 0 when zero is meaningful.
Mini Example: Login Gate
// Simple login gate
const username = "dev_ada";
const password = "correct-horse";
const attempts = 1;
const maxAttempts = 3;
if (!username || !password) {
console.log("Missing credentials");
} else if (attempts > maxAttempts) {
console.log("Account locked");
} else if (password === "correct-horse") {
console.log(`Welcome, ${username}`);
} else {
console.log("Invalid password");
}FAQ
Can I use if without braces for one line?
Yes—if (x) doThing(); is legal. Many teams still require {} for consistency and safer edits.
How many else if should I allow?
If a chain grows large, consider switch (next chapter) or a lookup object/map.
Is if (flag === true) bad style?
Often redundant when flag is already boolean—use if (flag).
What comes next?
Switch statements, then for and while loops in the following chapters.