Switch case construct
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.
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
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
Let's consider the simplest example :
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.
Consider this example :
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 :
On this :
The result will be the same, but the code will become more readable and easier to work with.
Problems?
Write to Discord chat.
Questions:
Is it possible to use switch
to compare something with regular expressions?
- Yes
- No
What comparison operator does switch
use?
=
===
==
Which keyword stops the comparison process in switch
?
break
stop
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.
Links
Contributors ✨
Thanks goes to these wonderful people (emoji key):
Philipp Dvinyaninov | Dmitriy Vasilev 💵 | Resoner2005 🐛 🎨 🖋 | Navernoss 🖋 🐛 🎨 |