The switch statement in JS controls the flow by executing different code blocks based on the value of the expression. It contains case statements (which specify the values to compare) and break statements (which jump out of the switch), and provides an optional default case (which handles all other values).
Usage of switch statement in JS
The switch statement is a control flow statement that is used to control the flow according to a certain The value of the expression executes a different block of code. It can handle multiple cases and provides a default case to handle all other values.
Syntax:
<code class="javascript">switch (expression) { case value1: // 为 value1 执行的代码 break; case value2: // 为 value2 执行的代码 break; // ...其他 case default: // 为所有其他值执行的代码(可选) break; }</code>
Usage steps:
Example:
<code class="javascript">let grade = 'A'; switch (grade) { case 'A': console.log('优秀'); break; case 'B': console.log('良好'); break; case 'C': console.log('及格'); break; default: console.log('不及格'); break; }</code>
Output:
<code>优秀</code>
Notes:
The above is the detailed content of How to use switch statement in js. For more information, please follow other related articles on the PHP Chinese website!