JavaScript If Else & Switch
JavaScript If Else & Switch is a core JavaScript concept covering javaScript If Else & Switch: The switch statement is used to perform This topic is essential for academic learning, board exam preparation, and developing optimized real-world code.
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:
- If score > 90: Grade A
- Else If score > 80: Grade B
- Else: Grade C
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.
If you omit the break statement, the next case will be executed even if the evaluation does not match the case.