If, Else, and Switch Statements
Conditional statements let you control the flow of your program based on conditions. JavaScript provides if, else if, else, and switch statements for this purpose.
✅ 1. if
Statement
Executes a block of code if a condition is true.
let age = 18;
if (age >= 18) {
console.log("You are an adult.");
}
✅ 2. if...else
Statement
Provides an alternative if the condition is false.
let isLoggedIn = false;
if (isLoggedIn) {
console.log("Welcome back!");
} else {
console.log("Please log in.");
}
✅ 3. if...else if...else
Chain
Checks multiple conditions in order.
let score = 75;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 75) {
console.log("Grade: B");
} else {
console.log("Grade: C");
}
🔁 4. switch
Statement
A cleaner way to compare a variable against many values.
let day = "Wednesday";
switch (day) {
case "Monday":
console.log("Start of the week");
break;
case "Wednesday":
console.log("Midweek day");
break;
case "Friday":
console.log("End of the week");
break;
default:
console.log("Regular day");
}
⚠️ Always use
break
to prevent fall-through between cases.
🎯 Summary
if
– Run code if condition is trueelse
– Run alternative codeelse if
– Check multiple conditionsswitch
– Compare one value against many possible matches
✅ Tip: Use
switch
when checking one variable against multiple fixed values. Use if
for more flexible or complex conditions.