JavaScript Control Statements β if, switch
After completing this topic
You will be able to create conditional branches using if, else if, and else, and you will understand when to use switch.
Execute Differently Based on Conditions
Programs don't always do the same thing. "Show the dashboard if the user is logged in, and show the login page if they are not" β creating these branches is what conditional statements are for.
const score = 85;
if (score >= 90) {
console.log("A grade");
} else if (score >= 80) {
console.log("B grade");
} else if (score >= 70) {
console.log("C grade");
} else {
console.log("Retake");
}
// Output: "B grade"Place the condition inside the parentheses after if. If the condition is true, the corresponding block is executed; if it's false, it moves to the next else if or else.
Comparison Operators and Logical Operators
These are the symbols used to compare values within conditional statements.
// Comparison operators
console.log(10 > 5); // true
console.log(10 === 10); // true (are the value and type both the same?)
console.log(10 == "10"); // true (are the values the same? β Don't use this)
console.log(10 !== 5); // true (are they not the same?)
// β οΈ Use === instead of ==
// == converts the type automatically for comparison β unexpected results may occur
console.log(0 == false); // true (dangerous!)
console.log(0 === false); // false (accurate!)// Logical operators β combine conditions
const age = 25;
const hasTicket = true;
// AND: true if both are true
if (age >= 18 && hasTicket) {
console.log("Admission allowed");
}
// OR: true if one is true
if (age < 13 || age >= 65) {
console.log("Discount applied");
}
// NOT: inverts true β false
if (!hasTicket) {
console.log("Please purchase a ticket");
}Using === instead of == is one of the most basic rules of JavaScript. == compares values after automatically converting the type, which can lead to unpredictable results.
switch β Multiple Branches Based on One Value
When you want to branch into multiple cases based on a single variable value, switch is a cleaner approach.
const day = "Mon";
switch (day) {
case "Mon":
case "Tue":
case "Wed":
case "Thu":
case "Fri":
console.log("Weekday");
break;
case "Sat":
case "Sun":
console.log("Weekend");
break;
default:
console.log("Invalid input");
}If you forget to include break, the execution will flow to the next case (fall-through). You can use this intentionally, but most of the time it's a mistake. Make it a habit to check if you've included break.