Home > Web Front-end > JS Tutorial > Detailed explanation of the usage of Switch statement in JavaScript

Detailed explanation of the usage of Switch statement in JavaScript

青灯夜游
Release: 2019-11-26 17:32:10
forward
4027 people have browsed it

In addition to if...else, JavaScript also has a feature called a switch statement. A switch is a conditional statement that will evaluate an expression against a number of possible situations and execute one or more blocks of code depending on the matching situation. The switch statement is closely related to the conditional statement that contains many other if blocks, and they are often used interchangeably.

Detailed explanation of the usage of Switch statement in JavaScript

In this tutorial, we will learn how to use the switch statement and how to use the related keywords case, break and default. Finally, we'll cover how to use multiple cases in a switch statement.

[Related course recommendations: JavaScript video tutorial]

Switch

switch statement calculation expression formula and execute the code as the result of matching case. It may seem a little intimidating at first, but the basic syntax is similar to an if statement. It will always be written using switch(){}, with parentheses containing the expression to be tested, and curly braces containing the underlying code to be executed.

The following is an example of a switch statement with two case statements and a fallback called default.

switch (expression) {
    case x:        
    // execute case x code block
        break;    
     case y:
     // execute case y code block
        break;   
      default:        
      // execute default code block
      }
Copy after login

Following the logic of the code block above, this is the sequence of events that will occur:

Expression is evaluated

In the first case, x will be tested against the expression . If there is a match, the code will execute and the break keyword will end the switch block.

If it does not match, x will be skipped and y will be tested against the expression case. If y matches the expression, the code will execute and exit the switch block.

If all conditions are not matched, the default code block will be run.

Let’s make a working example of a switch statement following the above syntax. In this code block, we will use the new Date() method to find the current day of the week and getDay() to print the number corresponding to the current day. 1 stands for Monday and 7 stands for Sunday. We'll start by setting up variables.

const day = new Date().getDay();
Copy after login

Using switch we will send a message to the console every day of the week. The program will run in order from top to bottom looking for matches, and once one is found, the break command will stop the switch block and continue evaluating the statement.

week.js

// Set the current day of the week to a variable, with 1 being Monday and 7 being Sunday
const day = new Date().getDay();
switch (day) {
    case 1:
        console.log("Happy Monday!");        
        break;    
    case 2:
        console.log("It's Tuesday. You got this!");        
        break;    
    case 3:
        console.log("Hump day already!");        
        break;    
    case 4:
        console.log("Just one more day 'til the weekend!");        
        break;    
     case 5:
        console.log("Happy Friday!");        
        break;    
      case 6:
        console.log("Have a wonderful Saturday!");        
        break;    
      case 7:
        console.log("It's Sunday, time to relax!");        
        break;    
      default:
        console.log("Something went horribly wrong...");
}
Copy after login
Output
'Just one more day 'til the weekend!'
Copy after login

This code was tested on Thursday, which corresponds to 4, so the console output is Just one more day 'til the weekend!. Depending on the day of the week you test your code, your output will vary. We include a block by default at the end to run in case of an error, which should not happen in this case since there are only 7 days in a week. For example, we might also only have print results from Monday to Friday, and the default block might have the same information for weekends as well.

If we omit the break keyword in each statement, none of the other case statements will evaluate to true, but the program will continue checking until it reaches the end. To make our program faster and more efficient, we include break.

Switch Ranges

There is a situation where you need to evaluate a range of values ​​in a switch block instead of like in the example above single value. We can do this by setting the expression to true and performing the action in each case statement.

To make this easier to understand, we made a simple grading app that will take a numeric score and convert it to a letter grade, with the following requirements.

● Level 90 and above is A

● Level 80 to 89 is B

● Level 70 to 79 is C

● Level 60 to 69 is D

● Level 59 or below is F

Now we can write it as a switch statement. Since we are checking the range, we will do something in each case to check if each expression is evaluating to true, and then break out the statement once the true requirement is met.

grades.js

// Set the student's grade
const grade = 87;
switch (true) {
    // If score is 90 or greater
    case grade >= 90:
        console.log("A");       
        break;    
     // If score is 80 or greater
    case grade >= 80:
        console.log("B");        
        break;    
     // If score is 70 or greater
    case grade >= 70:
        console.log("C");       
        break;    
      // If score is 60 or greater
    case grade >= 60:
        console.log("D");        
        break;    
      // Anything 59 or below is failing
    default:
        console.log("F");
}
Copy after login
Output
'B'
Copy after login

In this example, the expression in the brackets is evaluated to true. This means that anything that evaluates to true is a match.

Just like using else, switch evaluates from top to bottom and accepts the first true match. So even though our rank variable is 87 and therefore evaluates to true for C and D, the first match is B and it will be the output.

Multiple Cases

You may encounter code where multiple cases should have the same output. To achieve this, you can use multiple cases for each code block.

To test this, we will make a small application that matches the current month with the appropriate season. First, we will use the new Date() method to find the number corresponding to the current month and apply it to the month variable.

For simplicity, our application will output the four seasons with the following specifications:

● Winter: January, February and March

● Spring: April , May and June

●Summer: July, August and September

●Autumn: October, November and December

以下是我们的代码。

seasons.js

// Get number corresponding to the current month, with 0 being January and 11 being December
const month = new Date().getMonth();
switch (month) {
    // January, February, March
    case 0:    
    case 1:    
    case 2:
        console.log("Winter");        
        break;    
    // April, May, June
    case 3:    
    case 4:    
    case 5:
        console.log("Spring");        
        break;    
    // July, August, September
    case 6:    
    case 7:    
    case 8:
        console.log("Summer");        
        break;    
    // October, November, December
    case 9:    
    case 10:    
    case 11:
        console.log("Autumn");        
        break;    
    default:
        console.log("Something went wrong.");
   }
Copy after login

当我们运行代码时,我们将根据上面的规范接收识别当前季节的输出。

Output
Summer
Copy after login

出版时的当月是8,这与“夏季”季节产出的一个case陈述相对应。

结论:

在本文中,我们回顾了switch语句,这是一种条件语句,用于评估表达式并根据匹配结果输出不同的值。 我们使用范围和多个case语句检查了switch语句。

本文来自 js教程 栏目,欢迎学习!

The above is the detailed content of Detailed explanation of the usage of Switch statement in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:digitalocean.com
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