Conditional Statements (if, else-if, switch)
Conditional statements allow your code to make intelligent decisions based on varying user input and data conditions.
What is it?
Conditionals execute specific blocks of code only when designated conditions evaluate to true. In JavaScript, conditionals include `if`, `else if`, `else`, and `switch` statements.
Why is it used?
Controls user authentication flows, form validation errors, permission checks, and page routing.
Detailed Explanation
• `if (condition)`: Executes code if condition is truthy.
• `else if`: Evaluates additional conditions in sequence.
• `else`: Fallback block if none of the preceding conditions met.
• `switch (expression)`: Efficient alternative to lengthy `else-if` chains when checking a single variable against multiple exact values. Always remember `break;` to prevent fall-through!
Syntax Structure
Syntax Blueprint
if (score >= 90) {
grade = 'A';
} else if (score >= 75) {
grade = 'B';
} else {
grade = 'C';
}
Code Example
JAVASCRIPT Code
// Course Level Evaluation System
function evaluateCourseLevel(durationWeeks) {
let level = "";
if (durationWeeks <= 4) {
level = "Fast-Track Beginner";
} else if (durationWeeks <= 8) {
level = "Comprehensive Intermediate";
} else if (durationWeeks <= 12) {
level = "Advanced Masterclass";
} else {
level = "Professional Diploma";
}
return level;
}
// Role Authorization with switch statement
function getRedirectUrl(role) {
switch (role) {
case "admin":
return "/admin/dashboard";
case "student":
return "/tutorial";
case "guest":
default:
return "/courses";
}
}
console.log(evaluateCourseLevel(6)); // "Comprehensive Intermediate"
console.log(getRedirectUrl("admin")); // "/admin/dashboard"
console.log(getRedirectUrl("guest")); // "/courses"
Explanation of the Code
• `evaluateCourseLevel` uses numeric range comparison with `else if`.
• `getRedirectUrl` uses a `switch` statement with clean `break`/`return` cases and a `default` safety fallback.
Expected Output
Comprehensive Intermediate
/admin/dashboard
/courses
Real-World Application
Used in web navigation routers, role-based access control (RBAC), and user login flows.
Common Mistakes to Avoid
• Omitting `break` in a `switch` statement, causing unintentional execution fall-through to the next case.
• Using assignment `=` instead of equality `===` inside `if` conditions.
Quick Practice Challenge
Write a function that accepts an age and returns 'Minor' if under 18, 'Adult' if between 18 and 59, and 'Senior Citizen' if 60 or above.
Key Takeaways
• Use `if` / `else if` / `else` for range and complex boolean checks.
• Use `switch` when matching a single variable against discrete constant values.
• Remember truthy and falsy values (`0`, `""`, `null`, `undefined`, `NaN` are falsy).