Home > Web Front-end > JS Tutorial > body text

How to use switch statement in js

下次还敢
Release: 2024-05-01 04:42:16
Original
521 people have browsed it

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).

How to use switch statement in js

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>
Copy after login

Usage steps:

  1. Expression: Specify the desired Evaluated expression. Expressions can be of any data type (number, string, boolean, etc.).
  2. case: Each case specifies the value to be compared. It can be a constant value, variable or expression.
  3. Code block: case is followed by the code block to be executed.
  4. break: Each case must be followed by a break statement to jump out of the switch statement and continue executing subsequent code. If break is omitted, when a case is matched, execution of subsequent cases will continue.
  5. default: default case is optional and will be executed when all other cases are not matched.

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>
Copy after login

Output:

<code>优秀</code>
Copy after login

Notes:

  • case values ​​must be unique and not repeated.
  • The case and default in the switch statement must be separated by break.
  • If no case is matched, the default case will be executed.
  • Switch statements can be nested within other control flow statements, such as if statements or for loops.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!