Js Switch in JavaScript
? JavaScript switch Statement
The switch statement is a control structure used to perform different actions based on different possible values of an expression. It’s an alternative to using multiple if...else if statements when comparing the same variable against different values.
Syntax
switch (expression) { case value1: // code to execute if expression === value1 break; case value2: // code to execute if expression === value2 break; // more cases... default: // code to execute if no case matches}How It Works
The
expressionis evaluated once.Its result is compared to the values in each
case(using strict equality===).If a match is found, the code block under that
caseruns.The
breakstatement prevents "fall-through" to the next case.If no case matches, the
defaultblock (optional) runs.
Example
let day = 3;let dayName;switch (day) { case 1: dayName = "Monday"; break; case 2: dayName = "Tuesday"; break; case 3: dayName = "Wednesday"; break; case 4: dayName = "Thursday"; break; case 5: dayName = "Friday"; break; default: dayName = "Weekend";}console.log(dayName); // Output: WednesdayNotes
Omitting
breakcauses fall-through (execution continues to the next case).Multiple cases can share the same code:
switch (fruit) { case 'apple': case 'banana': console.log("This is a common fruit."); break; case 'dragonfruit': console.log("Exotic fruit!"); break;}If you want, I can help you with more examples or explain fall-through behavior!