Understanding if...else if in JavaScript

๐Ÿ“˜ What is if...else if?

The if...else if statement lets you check multiple conditions one after the other in JavaScript. It's an extension of the if and else structure, allowing for more flexible decision-making.

>>โ€œCode is logic made visible โ€” and else if brings clarity to your choices.โ€ ๐Ÿงญ

๐Ÿ“Œ Syntax

Basic Syntax

if (condition1) {
  // executes if condition1 is true
} else if (condition2) {
  // executes if condition2 is true
} else {
  // executes if none of the above conditions are true
}

๐ŸŒ Real-Life Example

if...else if Example

const hour = 14;

if (hour < 12) {
  console.log("๐ŸŒ… Good morning");
} else if (hour < 18) {
  console.log("๐ŸŒž Good afternoon");
} else if (hour < 21) {
  console.log("๐ŸŒ‡ Good evening");
} else {
  console.log("๐ŸŒ™ Good night");
}

๐Ÿง  How it Works

JavaScript evaluates each condition in order:

  • If condition1 is true, it runs that block and skips the rest.
  • If condition1 is false, it checks condition2.
  • If no conditions match, the else block (if provided) runs.

๐Ÿ’ก Example: Grade Evaluator

Grade Based on Score

const score = 76;

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");
}

โš ๏ธ Best Practices

Note

Keep if...else if blocks readable. If you're checking too many cases, consider using a switch statement or mapping logic to functions or objects.

โœจ Ternary Isnโ€™t Ideal Here

While the ternary operator is great for simple if...else cases, it becomes unreadable when chaining multiple conditions. Use if...else if for clarity.

๐Ÿ“š Further Learning

>>โ€œComplex decisions demand clarity โ€” and else if is your tool for building that logic.โ€ ๐Ÿง