Javascript Switch

Javascript Switch

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

switch (expression) { case value1: // Code to execute if expression === value1 break; case value2: // Code to execute if expression === value2 break; default: // Code to execute if none of the cases match }
  • expression is compared (===) with each case.
  • break prevents execution from falling to the next case.
  • default runs if no match is found.

2️⃣ Example: Simple switch

let fruit = "apple"; switch (fruit) { case "banana": console.log("Bananas are yellow."); break; case "apple": console.log("Apples are red."); break; case "grape": console.log("Grapes are purple."); break; default: console.log("Unknown fruit."); }

šŸ“Œ Output: "Apples are red."

3️⃣ default Case

Runs when no cases match.

let color = "blue"; switch (color) { case "red": console.log("Red like fire."); break; case "green": console.log("Green like grass."); break; default: console.log("Color not recognized."); }

šŸ“Œ Output: "Color not recognized."

4️⃣ Multiple Cases, Same Output

Cases can share the same code.

let day = "Saturday"; switch (day) { case "Saturday": case "Sunday": console.log("It's the weekend!"); break; case "Monday": case "Tuesday": case "Wednesday": case "Thursday": case "Friday": console.log("It's a weekday."); break; default: console.log("Invalid day."); }

šŸ“Œ Output: "It's the weekend!" (if day = "Saturday")

5️⃣ switch Without break (Fall-through)

If break is omitted, execution continues to the next case.

let grade = "B"; switch (grade) { case "A": console.log("Excellent!"); case "B": console.log("Good job!"); case "C": console.log("You passed."); break; default: console.log("Try again."); }

šŸ“Œ Output:

Good job! You passed.

🚨 Warning: Use break to avoid unintended behavior.

6️⃣ switch with Expressions

You can use mathematical expressions.

let num = 10; switch (true) { case num < 10: console.log("Number is less than 10."); break; case num === 10: console.log("Number is exactly 10."); break; case num > 10: console.log("Number is greater than 10."); break; }

šŸ“Œ 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. 😊

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close