Detailed explanation of the usage of Switch statement in JavaScript
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.
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 }
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();
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..."); }
Output 'Just one more day 'til the weekend!'
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"); }
Output 'B'
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."); }
当我们运行代码时,我们将根据上面的规范接收识别当前季节的输出。
Output Summer
出版时的当月是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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Can Elden's Ring be played on the switch? As a very charming action RPG game, many friends may not know whether it can be played smoothly on the switch platform. The answer is that it cannot be played at the moment. accomplish. Can Ring of Elden be played on switch? Answer: It cannot be played on switch. This highly anticipated Souls series role-playing action game has been officially released. Players can purchase it on PC, PS4/5 and Xbox Series eX|S/XboxOne and experience it immediately. Many friends who own a switch may still be eager to enjoy this game on the NS, but unfortunately, there is no switch version of the game. According to the official website configuration requirements, the game configuration is relatively high, and sw

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Switch2 is a new model announced by Nintendo at Gamescom 2023. Some players are worried about whether there will be compatibility issues between the new model and the cartridges of previous versions. Let’s take a look. Is switch2 compatible with switch cassette? Answer: switch2 is not compatible with switch cassette. Introduction of Switch 2 cartridges According to information from Nintendo’s production chain company, Switch 2 may use 64GB cartridges. Because it has better performance and supports more 3A game masterpieces, it requires a larger cartridge capacity. Because many game works need to be castrated and compressed before they can be stuffed into a game cartridge. Moreover, Switch cartridges are prone to copying game content, so replace them with new cartridges.

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

JavaScript and WebSocket: Building an efficient real-time search engine Introduction: With the development of the Internet, users have higher and higher requirements for real-time search engines. When searching with traditional search engines, users need to click the search button to get results. This method cannot meet users' needs for real-time search results. Therefore, using JavaScript and WebSocket technology to implement real-time search engines has become a hot topic. This article will introduce in detail the use of JavaScript

Overview of how to use WebSocket and JavaScript to implement an online electronic signature system: With the advent of the digital age, electronic signatures are widely used in various industries to replace traditional paper signatures. As a full-duplex communication protocol, WebSocket can perform real-time two-way data transmission with the server. Combined with JavaScript, an online electronic signature system can be implemented. This article will introduce how to use WebSocket and JavaScript to develop a simple online

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

Switchcase requires specific code examples to determine variables. In programming, we often need to perform different operations based on different variable values. The switchcase statement is a convenient structure that allows you to select different blocks of code for execution based on the value of a variable. The following is a specific code example that shows how to use the switchcase statement to determine different values of variables: #includeintmain(){
