JavaScript Switch Statement
In this tutorial:
The switch statement in JavaScript
JavaScript switch statement with default clause
Use of break statement
The switch Statement in JavaScript
In JavaScript, switch statements are used to control complex conditional operations. Sometimes nested if...else statements become complex, whereas switch...case statement offers simple and cleaner syntax to implement same logic.
Syntax:
switch (expression) {
case value1:
statements
case value2:
statements
// …
case valueN:
statements
default:
statements
}
- The switch statement is used when you have to select one choice from multiple choices on the basis of result of expression.
- The expression is evaluated.
- It looks for the first
caseclause whose value matches against expression value. - The control passes to that case clause.
- The execution starts from the first statement after the matching case clause.
- The execution continues until either the
breakstatement is encountered or execution reaches the end of the switch statement. - If a
breakstatement is encountered, subsequent case clause values will not be evaluated and control is transferred to the end of the switch statement. - The switch statement can include any number of case clauses.
- If no case clause matches the expression, control transfers to the
defaultstatement and statements following that clause are executed. In case, there is no default clause, control is transferred to the end of the switch statement. - The
defaultclause is optional. - Note: Internally, switch cases use strict comparison (===). The values must be of the same type to match.
Let’s try the following example.
let month = 3
switch (month) {
case 1:
console.log("January");
break;
case 2:
console.log("February");
break;
case 3:
console.log("March");
break;
case 4:
console.log("April");
break;
case 5:
console.log("May");
break;
case 6:
console.log("June");
}
In the above example,
let month = 3;- This line declares a variablemonthand assigns it the value3. This value represents the month number.- The
switchstatement evaluates the value of the variablemonth. It checks the value against different cases usingcasestatements. - In this scenario,
monthis assigned the value3. Therefore, when theswitchstatement is evaluated, it matches thecase 3:statement. - The code within the
case 3:block is executed, which containsconsole.log("March");. This statement prints "March" to the console usingconsole.log(). - The
break;statement is used after eachcaseblock. It's important because it tells JavaScript to exit theswitchstatement after executing the code within the matchedcase. Withoutbreak;, JavaScript would continue to execute the code for subsequent cases even after finding a match. - In this specific code snippet, if
monthhad a value other than 1, 2, 3, 4, 5, or 6, nothing would be printed.
JavaScript switch Statement With Default Clause
A switch statement may also have a default clause. If the expression does not match to any case clause value, the default clause is executed.
let month = 7
switch (month) {
case 1:
console.log("January");
break;
case 2:
console.log("February");
break;
case 3:
console.log("March");
break;
case 4:
console.log("April");
break;
case 5:
console.log("May");
break;
case 6:
console.log("June");
break;
default:
console.log("Unknown Month");
}
//output: Unknown Month
let month = 7;- This line declares a variablemonthand assigns it the value7. This value represents the month number.- The
switchstatement evaluates the value of the variablemonthagainst different cases usingcasestatements. - In this scenario,
monthis assigned the value7. When theswitchstatement is evaluated, it doesn’t match any of the definedcasestatements (1 through 6). - Since none of the
casestatements match the value ofmonth(which is7in this case), the code executes thedefault:case. -
The code within the
default:block is executed, which containsconsole.log("Unknown Month");. This statement prints "Unknown Month" to the console usingconsole.log(). - The
default:case is used as a fallback for values that don't match any of the specifiedcasestatements. It provides a way to handle scenarios where the value ofmonthdoesn't match any explicitly defined cases.
In short, in the above example, since month has a value of 7, which does not match any of the defined cases (1 through 6), the default: case is executed, and it prints "Unknown Month" to the console.
Use of break Statement
Let’s try another example, and see how the program executes in the absence of a break statement in a case clause.
let month = 3
switch (month) {
case 1:
console.log("January");
break;
case 2:
console.log("February");
break;
case 3:
console.log("March");
case 4:
console.log("April");
case 5:
console.log("May");
case 6:
console.log("June");
default:
console.log(“Unknown Month”);
}
//Output:
March
April
May
June
Unknown Month
Here is the sequence of code flow.
let month = 3;: This line declares a variablemonthand assigns it the value3, representing the month of March.- The
switchstatement is used to evaluate the value of the variablemonthagainst different cases. - In this scenario:
- When
monthis3, it matches thecase 3:statement, and the code block associated withcase 3:is executed:console.log("March");. - Unlike the previous
casestatements (e.g.,case 1:,case 2:) which include abreak;statement after theconsole.log()statement, thecase 3:block lacks abreak;statement.
- When
- The absence of a
break;statement in thecase 3:block causes what is known as "fall-through" behavior. After executing the code block forcase 3:(printing "March"), the code continues to execute the subsequent cases (case 4:,case 5:,case 6:) without further checks for matching cases. This behavior is a consequence of nobreak;statement to exit the switch block. - As a result of the fall-through behavior:
- After printing "March," the code proceeds to execute the code blocks for
case 4:,case 5:, andcase 6:consecutively, printing "April," "May," and "June," respectively. - There is no
break;statement in these subsequent cases, causing the code to continue executing until the end of theswitchstatement.
- After printing "March," the code proceeds to execute the code blocks for
- In the above scenario where the
break;statement is absent, default clause is also executed along with case clause(s). So you need to be very careful in program flow control otherwise you may experience unexpected results..
Therefore, when month is 3 in this code snippet, the output will be:
//Output:
March
April
May
June
Unknown Month
The break; statement is crucial within each case block to prevent fall-through behavior. Without it, JavaScript will continue to execute code for subsequent cases after finding a match until it reaches a break; statement or the end of the switch block.
Summary
The switch statement evaluates an expression against multiple cases, executing the code block associated with the first matching case (along with its subsequent code) and exiting the switch statement unless break; is omitted, ensuring only the intended case's code is executed. If no cases match, the default block (if provided) is executed, or the switch statement finishes execution if there's no default case.