Skip to main content

Switch case construct

@serverSerrverlesskiy

The switch construction is used to compare a value for equality with different options.

In this case, equality is implied in the sense of the operator strict equality ===, it cannot compare with a regular expression or somehow else. That is, the values must be of the same type for equality to hold.

comparison

If the condition matches, then the code block associated with the corresponding case is executed. If none of the conditions match, then the code specified in the default block, if any, is executed. To exit the construction, use the break command. If you do not specify it, the code block is automatically executed in the next case, etc. Therefore, we use break in our scripts, so as not to run the interpreter over all cases, thereby reducing the performance of the script.

Syntax

Syntax

A switch construct has one or more case blocks and an optional default block.

It looks like this:

switch (n) {
case 1:
// code block 1;
break
case 2:
// code block 2;
break
// .......
// other case options
// .......
default:
// code block if none of the conditions match;
}

n - this is boolean condition.

Examples of

Math

Let's consider the simplest example :

Live Editor
Result
Loading...

Here the switch statement will sequentially compare a with all the options from case. First 3, then - since there is no match - 4. A match is found, this option will be executed, from the line str = 'To point!' And further, to the nearest break, which will interrupt the execution.

Wow

Consider this example :

Live Editor
Result
Loading...

Here the switch statement will sequentially compare a with all the options from case. But this is not a comparison of numbers, but of strings. This can be done with any data type, as long as the same data types are compared.

Replacing if

Also, Switch is used to replace multiple if.

For example, you can replace this code :

Live Editor
Result
Loading...

On this :

Live Editor
Result
Loading...

The result will be the same, but the code will become more readable and easier to work with.

EnglishMoji!

Problems?

Problem

Write to Discord chat.

Questions:

Question

Is it possible to use switch to compare something with regular expressions?

  1. Yes
  2. No

What comparison operator does switch use?

  1. =
  2. ===
  3. ==

Which keyword stops the comparison process in switch?

  1. break
  2. stop
  3. default

In order to understand how much you learned this lesson, take the test in the mobile application of our school on this topic or in our telegram bot.

EnglishMoji!

  1. MDN web docs
  2. Learn JavaScript
  3. Справочник JavaScript

Contributors ✨

Thanks goes to these wonderful people (emoji key):


Philipp Dvinyaninov


Dmitriy Vasilev

💵

Resoner2005

🐛 🎨 🖋

Navernoss

🖋 🐛 🎨