How to write a switch statement in JavaScript?
In JavaScript, a switch
statement is a control flow statement that evaluates an expression and executes code based on matching cases. It provides a more concise and readable way to handle multiple possible conditions compared to nested if...else
statements.
Syntax:
switch (expression) {
case value1:
// code block to be executed if expression matches value1
break;
case value2:
// code block to be executed if expression matches value2
break;
// more cases can be added as needed
default:
// code block to be executed if expression does not match any case
}
Parameters:
expression
: The expression whose value is compared against each case.value1
,value2
, etc.: The possible values thatexpression
may match.case
andbreak
: Eachcase
represents a possible value of the expression. When a case is matched, the associated code block is executed. Thebreak
statement is used to exit theswitch
statement and prevent fall-through to subsequent cases.default
: An optionaldefault
case that is executed ifexpression
does not match any of the specified cases.
Example: Here, the switch
statement evaluates the value of the day
variable. Depending on the value of day
, the corresponding case is matched, and the associated code block is executed. If none of the cases match, the default
case is executed. In this case, it day
is "Monday"
, the message “Today is Monday.” will be logged to the console.
Javascript
const day = "Monday" ; switch (day) { case "Monday" : console.log( "Today is Monday." ); break ; case "Tuesday" : console.log( "Today is Tuesday." ); break ; case "Wednesday" : console.log( "Today is Wednesday." ); break ; case "Thursday" : console.log( "Today is Thursday." ); break ; case "Friday" : console.log( "Today is Friday." ); break ; default : console.log( "It's a weekend day." ); } |
Output
Today is Monday.
Contact Us