The switch statement is a conditional statement in JavaScript that allows you to execute one block of code from multiple choices.
The switch statement evaluates an expression and compares its value with different cases.
Switch statements help simplify decision-making when there are many possible outcomes.
The expression is evaluated once and compared against each case value.
Case 4
Since the value of a is 4, case 4 is executed.
The break statement stops execution after a matching case is found.
Without break, JavaScript continues executing the next cases even if they do not match.
Switch statements can also work with string values.
This is Lavu
Multiple cases can share the same code block.
Case 1, 2 and 3 executed
The default case executes when none of the cases match the expression.
Color Not Found
If break is omitted, execution continues into the next cases. This is called Fall Through.
One
Two
Three
| Switch Statement | If Else Statement |
|---|---|
| Used for fixed values. | Used for complex conditions. |
| Easy to read. | Can become lengthy. |
| Better for many choices. | Better for ranges and logical expressions. |
| Uses case blocks. | Uses conditional expressions. |
A school management system can use switch to display class sections.
Class A
| Keyword | Purpose |
|---|---|
| switch | Starts the switch block |
| case | Checks a specific value |
| break | Stops execution |
| default | Executes when no case matches |
Which keyword is used to stop execution inside a switch statement?