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.โ ๐ง