Home >Web Front-end >JS Tutorial >How to use switch in js
The switch statement in JavaScript is used to execute a specific block of code based on the variable value: compare the variable value and the case value. When matching, execute the corresponding code block and use break to exit. Executes the default block (optional) when there is no match.
The use of switch statement in JavaScript
The switch statement is used in JavaScript to compare the values of variables and execute the corresponding Conditional statements for code blocks. The syntax is as follows:
<code class="javascript">switch (expression) { case value1: // 当 expression 的值等于 value1 时执行的代码 break; case value2: // 当 expression 的值等于 value2 时执行的代码 break; ... default: // 当 expression 的值与所有 case 不匹配时执行的代码 }</code>
Instructions for use:
How it works:
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('不及格'); }</code>
Output:
<code>优秀</code>
Please note that the break statement is necessary to prevent the switch statement from executing subsequently case is crucial, without break the code will continue executing for all matching cases.
The above is the detailed content of How to use switch in js. For more information, please follow other related articles on the PHP Chinese website!