What Are Conditionals?
Conditionals let your code make decisions. They execute different blocks of code based on whether a condition is true or false.
💡 Real-world analogy
If it's raining, take an umbrella. Otherwise, don't. That's a conditional — a decision based on a condition.
The if Statement
The most basic conditional. If the condition is true, the code runs.
let age = 18;
if (age >= 18) {
console.log("You can vote!");
}
if/else — Two Paths
One path for when the condition is true, another for when it's false.
let temperature = 25;
if (temperature > 30) {
console.log("It's hot outside.");
} else {
console.log("It's pleasant outside.");
}
else if — Multiple Conditions
Check multiple conditions in sequence.
let score = 85;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B");
} else if (score >= 70) {
console.log("Grade: C");
} else {
console.log("Grade: F");
}
The Ternary Operator (?)
A shorthand for if/else when you have a simple condition.
let age = 20;
let status = age >= 18 ? "Adult" : "Minor";
console.log(status); // "Adult"
switch Statements
Useful when you're comparing the same value against many possibilities.
let day = "Monday";
switch (day) {
case "Monday":
console.log("Start of the work week");
break;
case "Friday":
console.log("TGIF!");
break;
case "Saturday":
case "Sunday":
console.log("Weekend!");
break;
default:
console.log("Midweek");
}
⚠️ Don't forget
break
Without break, execution "falls through" to the next case. This is often a bug unless you intentionally want fall-through behavior.
Truthy and Falsy Values
In JavaScript, conditions don't have to be strictly true or false. Some values are "truthy" and some are "falsy".
- Falsy:
false,0,""(empty string),null,undefined,NaN - Truthy: Everything else —
true,"hello",42,[],{}
Common Mistakes
- Using
=(assignment) instead of===(comparison) in conditions - Forgetting to use
breakinswitchstatements - Overcomplicating simple conditions — use the ternary operator for concise code
Quick Quiz
1. What will this code output?
let x = 5; if (x > 3) { console.log("A"); } else { console.log("B"); }
2. What does the ternary operator do?
3. Which of these is a falsy value?
Summary
ifruns code when a condition is trueif/elseprovides two pathselse ifallows multiple conditions- The ternary operator (
?) is a shorthand for simple if/else switchis useful for many comparisons of the same value- Remember falsy values:
false,0,"",null,undefined,NaN
