5. Conditional Statements in JavaScript
What Are Conditional Statements?
Conditional statements let your code make decisions. They check whether something is true or false and then decide what to do next — kind of like a mini decision tree in your program.
let temperature = 30;
if (temperature > 25) {
console.log("It's hot outside!");
}Here, the `if` block runs only if the condition inside the parentheses is true.
If, Else If, and Else
When you have multiple possibilities, you can chain conditions using `else if` and finish with a fallback `else` block.
let score = 82;
if (score >= 90) {
console.log("Excellent!");
} else if (score >= 70) {
console.log("Good job!");
} else {
console.log("Keep practicing!");
}JavaScript will run the first condition that’s true and skip the rest.
Comparison and Logical Operators Together
You can combine comparisons using logical operators like `&&` (AND) and `||` (OR) for more complex checks.
let age = 22;
let hasLicense = true;
if (age >= 18 && hasLicense) {
console.log("You can drive.");
} else {
console.log("You can’t drive yet.");
}The Switch Statement
When you need to compare the same variable against multiple values, a `switch` statement can make your code cleaner than writing lots of `else if` lines.
let day = "Tuesday";
switch (day) {
case "Monday":
console.log("Start of the week!");
break;
case "Friday":
console.log("Almost weekend!");
break;
case "Saturday":
case "Sunday":
console.log("Weekend vibes!");
break;
default:
console.log("Just another day.");
}Each `case` is checked in order, and the `break` statement stops JavaScript from checking the next one. If no case matches, the `default` block runs.
Ternary Operator
The ternary operator is a shorthand for simple `if...else` conditions. It uses the syntax: `condition ? valueIfTrue : valueIfFalse`.
let isMember = true;
let message = isMember ? "Welcome back!" : "Please sign up.";
console.log(message);Nested Conditionals
You can also place one conditional inside another. Just be careful not to make them too complicated or deeply nested — readability matters.
let time = 14;
let isWeekend = false;
if (time < 12) {
console.log("Good morning!");
} else {
if (isWeekend) {
console.log("Enjoy your afternoon off!");
} else {
console.log("Back to work!");
}
}Mini Challenge
Write a program that checks a variable `score` and prints: - "Excellent" if it’s 90 or above, - "Good" if it’s between 70 and 89, - "Needs Improvement" otherwise.
// Example:
let score = 68;
if (score >= 90) {
console.log("Excellent");
} else if (score >= 70) {
console.log("Good");
} else {
console.log("Needs Improvement");
}Key Takeaway
Conditionals bring logic and decision-making to your code. With `if`, `else`, and `switch`, your programs can respond dynamically to different inputs and situations.