Switch Case in Javascript
In JavaScript, the switch
statement is used to perform different actions based on different conditions. It evaluates an expression and then executes statements associated with the matching case label. Here's a basic syntax of the switch
statement:
javascriptCopy codeswitch (expression) {
case value1:
// Code to be executed if expression matches value1
break;
case value2:
// Code to be executed if expression matches value2
break;
// Add more cases as needed...
default:
// Code to be executed if expression doesn't match any case
}
expression
: The expression whose value is to be compared with the values of the case labels.case valueN
: The value to compare withexpression
. Ifexpression
matchesvalueN
, the code within the correspondingcase
block is executed.break
: Optional. It terminates theswitch
statement. If omitted, execution will continue to the next case block. Ifbreak
is not used, all the code blocks after the matched case will be executed.default
: Optional. It specifies the code to be executed if none of the case values match the expression.
Here's an example of how you can use the Switch statement in JavaScript:
javascriptCopy codelet day = new Date().getDay();
let dayName;
switch (day) {
case 0:
dayName = "Sunday";
break;
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;
case 6:
dayName = "Saturday";
break;
default:
dayName = "Invalid Day";
}
console.log("Today is " + dayName);
This code snippet uses the switch
statement to determine the day of the week based on the current day number (getDay()
returns a number from 0 to 6 representing the day of the week, starting from Sunday as 0). It assigns the corresponding day name to the dayName
variable and logs it to the console. Learn more free JavaScript tutorials!