Conditional statements in JavaScript allow you to perform different actions based on different conditions.
1. if, else if, and else
Executes a block of code if a condition is true.
let score = 75;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 70) {
console.log("Grade: B"); // Executes this block
} else {
console.log("Grade: F");
}
2. Ternary Operator (? :)
A concise shortcut for simple if...else assignments.
let age = 20;
let status = (age >= 18) ? "Adult" : "Minor";
console.log(status); // "Adult"
3. switch Statement
Evaluates an expression against multiple potential case matches using strict equality (===). Best when checking a single value against fixed options.
let day = "Monday";
switch (day) {
case "Monday":
console.log("Start of the work week!");
break; // Stops execution from falling through to the next case
case "Friday":
console.log("Weekend is near!");
break;
default:
console.log("Midweek day");
}
4. Logical Operators in Conditions
Combine multiple conditions using logical operators:
- && (AND): true only if both conditions are true.
- || (OR): true if at least one condition is true.
- ! (NOT): Inverts the boolean value.
let isAdult = true;
let hasTicket = false;
if (isAdult && hasTicket) {
console.log("Allowed entry.");
} else {
console.log("Entry denied."); // Executes this
}
Top comments (0)