Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use Switch, break and default of JavaScript

Shulou Source: shulou.com Published: 2022-06-01 05:38:52 09月22日 Update

This article mainly explains "how to use JavaScript's Switch, break and default". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to use JavaScript's Switch, break and default".

Break keyword

If JavaScript encounters a break keyword, it jumps out of the switch code block.

This will stop the execution of more code in the code block and case testing.

If a match is found and the task is completed, execution is randomly interrupted (break). No more tests are needed.

Break can save a lot of execution time because it "ignores" the execution of other code in the switch code block.

You don't have to interrupt the last case in the switch code block. The code block ends naturally here.

Default keyword

The default keyword specifies the code to run when there is no case match:

Example

The getDay () method returns the week name of the number 0 through 6.

If today is neither Saturday (6) nor Sunday (0), output a default message:

Switch (new Date (). GetDay () {

Case 6:

Text = "Today is Saturday"

Break

Case 0:

Text = "Today is Sunday"

Break

Default:

Text = "looking forward to the weekend -"

}

The result of text is:

Looking forward to the weekend--

The default case does not have to be the last case in the switch code block:

Example

Switch (new Date (). GetDay () {

Default:

Text = "looking forward to the weekend!"

Break

Case 6:

Text = "Today is Saturday"

Break

Case 0:

Text = "Today is Sunday"

}

If default is not the last case in the switch code block, remember to end the default case with break.

Common code blocks

Sometimes you need different case to use the same code.

In this example, case 4 and 5 share the same code block, while 0 and 6 share another code block:

Example

Switch (new Date (). GetDay () {

Case 4:

Case 5:

Text = "the weekend is coming:)"

Break

Case 0:

Case 6:

Text = "Today is the weekend -"

Break

Default:

Text = "looking forward to the weekend!"

}

Thank you for your reading, the above is the content of "how to use JavaScript's Switch, break and default". After the study of this article, I believe you have a deeper understanding of how to use JavaScript's Switch, break and default, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Code keys keywords examples more learning same content testing different tasks that is common ideas situations numbers articles methods time to make Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei Shulou Information MariaDB Redmi Linux