Conditional statements are used to perform different actions based on different conditions. They allow your program to make decisions and execute specific blocks of code only when certain criteria are met.
Use the if statement to specify a block of JavaScript code to be executed if a
condition is true.
if (condition) {
// block of code to be executed if the condition is true
}
Example: Greeting based on time.
if (hour < 12) {
greeting = "Good morning";
}
Use the else statement to specify a block of code to be executed if the
condition is false.
if (hour < 18) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
Use the else if statement to specify a new condition if the first condition is
false. You can use as many else if blocks as you need.
if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
You can put an if statement inside another if statement. This is
known as nesting.
if (userLoggedIn) {
if (hasSubscription) {
console.log("Welcome to Premium Content");
} else {
console.log("Please subscribe");
}
}
if: Executes code only if a condition is trueelse: Executes code if the same condition is falseelse if: Adds more conditions to the sequence(){}= instead of ==/===. if (isReady = true) assigns instead of comparing, and the condition is always truthy — a single missing character causes a silent logic bug.
if blocks are hard to follow. Prefer else if chains, or early return statements inside functions to flatten the logic.
{}, only the very next statement is conditional — adding a second line later without braces silently runs unconditionally.
A second example — turning a numeric score into a letter grade with an else-if chain:
let score = 82;
let grade;
if (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
} else if (score >= 70) {
grade = "C";
} else {
grade = "F";
}
console.log(grade); // "B"
Q: Can I use if without else?
A: Yes — else is entirely optional. Use a lone if when there's simply nothing to do when the condition is false.
Q: What's the difference between if/else and switch?
A: if/else handles ranges and complex conditions well. switch reads more cleanly when you're checking one variable against many exact values.
Q: Do I always need curly braces for a single-line if?
A: No, but it's strongly recommended — see the mistake above. The MDN if...else reference covers the exact block rules.