The if...else statement is a fundamental control structure in JavaScript that allows your code to make decisions based on conditions. It executes a block of code if a specified condition is true, and optionally another block if the condition is false.
📌 Deep Dive: Basic if...else Syntax
if (condition) {
// runs when condition is true
} else {
// runs when condition is false
}
Here, condition is a JavaScript expression that evaluates to true or false. Depending on the result, either the first or the second block executes.
📌 Deep Dive: Practical Example
const hour = 12;
if (hour < 18) {
console.log("Good day!");
} else {
console.log("Good evening!");
}

💡 Important
The else block is optional. If omitted, the code inside the if block runs only when the condition is true. Nothing happens if it's false.
📌 Deep Dive: Without else
const isLoggedIn = false;
if (isLoggedIn) {
console.log("Welcome back!");
}
// No else block, no output when false
if and if...else| Scenario | Behaviour |
|---|---|
if (condition) { ... } | Code runs only if condition is true. Nothing if false. |
if (condition) { ... } else { ... } | Runs one block: first if true, else the alternative block. |
⚠️ Common Pitfall
Use == or === for comparisons inside conditions. Assignment operator = will cause errors or unexpected behavior.
You can also chain multiple conditions using else if to handle more than two possibilities.
📌 Deep Dive: if...else if...else Chain
const score = 85;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B");
} else {
console.log("Grade: C or below");
}
💡 Tip
Conditions are evaluated from top to bottom. Once a true condition is found, the rest are skipped.
- Condition: A boolean expression evaluated to decide which block runs.
- if block: Code inside runs if condition is true.
- else block: Code inside runs if condition is false.
- else if: Additional condition checked if previous ones are false.
Mastering if...else statements equips you to create dynamic and responsive JavaScript programs by controlling the flow of execution.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
What happens if an if condition evaluates to false and there is no else block?
Question 2 of 2
Which operator should you use to check equality in an if condition?
Loading results...