JavaScript If Else & SwitchΒΆ
Conditional Logic (If-Else)ΒΆ
In programming, we often need to make decisions. Conditional logic allows a program to execute different pieces of code depending on whether a condition is true or false.
The "If" StatementΒΆ
This is like saying: "If it's raining, take an umbrella." If the condition is True, the code inside the block runs. If it's False, it is skipped.
The "Else" StatementΒΆ
This is the backup plan: "If it's raining, take an umbrella. Otherwise (Else), wear sunglasses."
The "Else If" (Elif) LadderΒΆ
When you have more than two options: 1. If score > 90: Grade A 2. Else If score > 80: Grade B 3. Else: Grade C
Logic First
Every conditional statement ultimately boils down to a Boolean value (True or False).
If, Else If, ElseΒΆ
if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
Switch StatementΒΆ
The switch statement is used to perform different actions based on different conditions.
switch(new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
Strict ComparisonΒΆ
Switch cases use strict comparison (===). The values must be of the same type to match.
Break is Important
If you omit the break statement, the next case will be executed even if the evaluation does not match the case.