JavaScript Control Flow
Control flow determines the order in which your code executes. Master if statements, switch cases, and logical operators to make your programs dynamic and responsive.
How do if, else and switch work in JavaScript?
if (condition) { … } runs a block only when the condition is truthy, else if checks further conditions in order, and else handles everything else. Use switch to compare one value against many exact cases, and the ternary condition ? a : b to choose between two values inside an expression.
if (score >= 90) {
grade = "A";
} else if (score >= 75) {
grade = "B";
} else {
grade = "C";
}
const label = isMember ? "Member price" : "Regular price";
switch (day) {
case "sat":
case "sun": type = "weekend"; break;
default: type = "weekday";
}If Statements
If statements are the foundation of control flow. They execute code only when a condition is true, allowing your programs to make decisions.
Basic If
if (condition) {
// code to execute
}Executes code only if condition is true
If-Else
if (condition) {
// if true
} else {
// if false
}Provides alternative path when condition fails
Else If Chain
if (condition1) {
// option 1
} else if (condition2) {
// option 2
} else {
// default
}Tests multiple conditions in sequence
Real-World Example: User Access Control
if (user.age >= 18 && user.hasAccount) {
// Allow full access
showAdultContent();
} else if (user.age >= 13) {
// Teen access with restrictions
showTeenContent();
} else {
// Child-safe content only
showKidsContent();
}Switch Statements
Switch statements are perfect when you need to compare a variable against many specific values. They're cleaner and more efficient than long if-else chains.
Basic Syntax
switch (variable) {
case 'value1':
// code for value1
break;
case 'value2':
// code for value2
break;
default:
// default code
}Key Points
Break Statement
Prevents fall-through to next case
Default Case
Handles unmatched values
Fall-through
Intentionally omit break for multiple cases
Real-World Example: Day of Week
switch (day) {
case 'Monday':
message = 'Start of work week';
break;
case 'Friday':
message = 'TGIF!';
break;
case 'Saturday':
case 'Sunday': // Fall-through for weekends
message = 'Weekend time!';
break;
default:
message = 'Regular day';
}Ternary Operator
The ternary operator provides a concise way to write simple if-else statements. It's perfect for quick conditional assignments.
Traditional If-Else
let message;
if (isLoggedIn) {
message = "Welcome!";
} else {
message = "Please log in";
}5 lines of code
Ternary Operator
let message = isLoggedIn
? "Welcome!"
: "Please log in";3 lines of code ✨
Common Use Cases
Variable Assignment
let status = age >= 18 ? 'adult' : 'minor';Function Arguments
console.log(score > 90 ? 'Excellent!' : 'Good job');CSS Classes
className = isActive ? 'btn-primary' : 'btn-secondary';Nested Ternary
level = score > 90 ? 'A' : score > 80 ? 'B' : 'C';Best Practice
Use ternary for simple conditions. For complex logic with multiple statements, stick with if-else for better readability.
Logical Operators
Logical operators allow you to combine multiple conditions, creating more sophisticated decision-making logic in your programs.
AND (&&)
if (age >= 18 && hasLicense) {
// Both must be true
}All conditions must be true
OR (||)
if (isVIP || isPremium) {
// Either can be true
}At least one condition must be true
NOT (!)
if (!isBlocked) {
// If not blocked
}Inverts the boolean value
Complex Conditions
Access Control Example
if ((age >= 18 && hasPermission) || isAdmin) {
// Allow access if:
// - Adult with permission, OR
// - Admin (regardless of age)
grantAccess();
} else {
denyAccess();
}Short-Circuit Evaluation
user && user.name && console.log(user.name);
// Only runs if user existsDefault Values
let name = user.name || 'Anonymous';
// Uses 'Anonymous' if user.name is falsyInteractive Control Flow Demo
Code Editor
<label>Score: <input id="score" type="number" value="82"></label>
<label>Day: <select id="day"><option>mon</option><option>sat</option><option>sun</option></select></label>
<pre id="out"></pre>Preview
What This Demo Shows:
- • If statements with multiple conditions
- • Switch statements with fall-through cases
- • Ternary operators for quick decisions
- • Logical operators combining conditions
- • Nested conditions and guard clauses
Best Practices & Common Patterns
✅ Do These
Use Clear Conditions
Make conditions readable and self-explanatory
if (user.isActive && user.hasPermission)Always Use Braces
Even for single statements
if (condition) { doSomething(); }Use Guard Clauses
Check for invalid conditions early
if (!user) return "Error";❌ Avoid These
Deep Nesting
Makes code hard to read and maintain
if (a) { if (b) { if (c) { ... } } }Missing Default Cases
Always handle unexpected values
switch without default caseComplex Ternary
Use if-else for complex logic
a ? b ? c ? d : e : f : gCommon Control Flow Patterns
Feature Flags
if (features.newUI) showNewUI();Input Validation
if (!email) return "Email required";State Management
switch (status) { case 'loading': ... }Control flow — step by step
if / else if / else — conditional branching
JavaScript evaluates the condition and executes the first matching branch. Conditions are coerced to boolean — truthy/falsy rules apply. Ternary (condition ? a : b) for inline single-expression choices. Avoid deeply nested if chains — extract conditions into named booleans or switch to early returns for clarity.
🎯 Quick Check
What does 'fall-through' mean in a switch statement?
JavaScript Conditionals: summary
Key points
- Conditions use truthiness:
if (items.length)is true when the array isn't empty. switchcompares with===, and withoutbreakexecution "falls through" to the next case.- Return early (guard clauses) to avoid deep nesting:
if (!user) return;. - Don't nest ternaries; use
if/elsewhen there are more than two outcomes.
Frequently asked questions
›When should I use switch instead of if/else?
When you compare one variable against several exact values. For ranges or complex conditions, use if/else if. An object lookup (map[key]) is often cleaner than either.
›What is a ternary operator?
A one-line if/else that produces a value: condition ? valueIfTrue : valueIfFalse.