If...Else Statements

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

JAVASCRIPT
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

JAVASCRIPT
const hour = 12;

if (hour < 18) {
  console.log("Good day!");
} else {
  console.log("Good evening!");
}
Output
Good day!
Illustration of if_else_statements
Illustration of if_else_statements

💡 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

JAVASCRIPT
const isLoggedIn = false;

if (isLoggedIn) {
  console.log("Welcome back!");
}

// No else block, no output when false
Comparison of if and if...else
ScenarioBehaviour
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

JAVASCRIPT
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");
}
Output
Grade: B

💡 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.