
JavaScript Switch Conditional Statement
The switch statement is used to perform different actions based on different conditions. The switch statement is used to select one of many code blocks to be executed. The switch statement evaluates an expression, compares its result with case values, and executes the statement associated with the matching case value.
Syntax
switch (expression) { case value1 : statement1; break; case value2: statement2; break; case value3: statement3; break; default: statement; }
How it works.
===
).The switch statement is like the if, else if statement. But it has more readable syntax.
The following example uses the switch statement to get the day of the week based on a day number:
let day = 3; let dayName; switch (day) { case 1: dayName = 'Sunday'; break; case 2: dayName = 'Monday'; break; case 3: dayName = 'Tuesday'; break; case 4: dayName = 'Wednesday'; break; case 5: dayName = 'Thursday'; break; case 6: dayName = 'Friday'; break; case 7: dayName = 'Saturday'; break; default: dayName = 'Invalid day'; } console.log(dayName); //Tuesday
How it works.
First, declare the day variable that holds the day number and the day name variable (dayName).
Second, get the day of the week based on the day number using the switch statement. If the day is 1
, the day of the week is Sunday. If the day is 2
, the day of the week is Monday, and so on.
Third, output the day of the week to the console.
===
) to compare the expression with the case values.