JavaScript switch
Statement š
The switch
statement is used for multiple conditional checks, making the code cleaner than multiple if...else if...else
statements.
1️⃣ Basic Syntax
expression
is compared (===) with eachcase
.break
prevents execution from falling to the next case.default
runs if no match is found.
2️⃣ Example: Simple switch
š Output: "Apples are red."
3️⃣ default
Case
Runs when no cases match.
š Output: "Color not recognized."
4️⃣ Multiple Cases, Same Output
Cases can share the same code.
š Output: "It's the weekend!"
(if day = "Saturday"
)
5️⃣ switch
Without break
(Fall-through)
If break
is omitted, execution continues to the next case.
š Output:
šØ Warning: Use break
to avoid unintended behavior.
6️⃣ switch
with Expressions
You can use mathematical expressions.
š Output: "Number is exactly 10."
šÆ Summary
✅ switch
is useful for multiple conditions
✅ break
prevents fall-through
✅ default
handles unmatched cases
✅ Multiple cases can share code
✅ switch (true)
can handle range conditions
š Now you can use switch
efficiently! Let me know if you have any questions. š