Switch design

Lecture




  1. Syntax
  2. Work example
  3. case grouping
  4. Type matters

The switch construct replaces several if once.

This is a more visual way of comparing an expression with several options at once.

Syntax

It looks like this:

01 switch (x) {
02    case 'value1' : // if (x === 'value1')
03      ...
04      [ break ]
05
06    case 'value2' : // if (x === 'value2')
07      ...
08      [ break ]
09
10    default :
11      ...
12      [ break ]
13 }

  • The variable x checked for strict equality to the first value of value1 , then to the second value2 and so on.
  • If a match is established, the switch starts executing from the corresponding case directive and on to the closest break (or to the end of the switch ).

    In this case is called the switch options .

  • If none of the case match, the default option is executed (if any).

Work example

An example of using a switch (the code that worked is highlighted):

01 var a = 2+2;
02
03 switch (a) {
04    case 3:
05      alert( 'Маловато' );
06      break ;
07    case 4:
08      alert( 'В точку!' );
09      break ;
10    case 5:
11      alert( 'Перебор' );
12      break ;
13    default :
14      alert( 'Я таких значений не знаю' );
15 }

Only one value will be displayed corresponding to 4 . After that break will abort execution.

If it is not interrupted, it will go further, while the remaining checks are ignored.

For example:

01 var a = 2+2;
02
03 switch (a) {
04    case 3:
05      alert( 'Маловато' );
06    case 4:
07      alert( 'В точку!' );
08    case 5:
09      alert( 'Перебор' );
10    default :
11      alert( 'Я таких значений не знаю' );
12 }

In the example above, three alert be executed in sequence.

alert( 'В точку!' );
alert( 'Перебор' );
alert( 'Я таких значений не знаю' );

In case can be any expressions , including variables and functions.

For example:

01 var a = 1;
02 var b = 0;
03
04 switch (a) {
05    case b+1:
06      alert(1);
07      break ;
08
09    default :
10      alert( 'нет-нет, выполнится вариант выше' )
11 }

case grouping

Multiple case values ​​can be grouped.

In the example below, case 3 and case 5 execute the same code:

01 var a = 2+2;
02
03 switch (a) {
04    case 4:
05      alert( 'Верно!' );
06      break ;
07
08    case 3: // (*)
09    case 5: // (**)
10      alert( 'Неверно!' );
11      break ;
12
13    default :
14      alert( 'Я таких значений не знаю' );
15 }

With case 3 execution goes from line (3) and goes down to the nearest break , thus passing what is intended for case 5 .

Importance: 5

Write an if..else corresponding to the following switch :

01 switch (browser) {
02    case 'IE' :
03      alert( 'О, да у вас IE!' );
04      break ;
05
06    case 'Chrome' :
07    case 'Firefox' :
08    case 'Safari' :
09    case 'Opera' :
10      alert( 'Да, и эти браузеры мы поддерживаем' );
11      break ;
12
13    default :
14      alert( 'Мы надеемся, что и в вашем браузере все ок!' );
15 }

Decision

If the condition is strictly followed, the comparison should be strict '===' .

In the real case, the usual comparison is likely to be '==' .

1 if (browser == 'IE' ) {
2    alert( 'О, да у вас IE!' );
3 } else if (browser == 'Chrome' || browser == 'Firefox'
4    || browser == || browser == 'Safari' || browser == || browser == 'Opera' ) {
5    alert( 'Да, и эти браузеры мы поддерживаем' );
6 } else {
7    alert( 'Мы надеемся, что и в вашем браузере все ок!' );
8 }

As you can see, this record is much worse read than the switch construction.

[Open task in new window]

Type matters

The following example takes value from the visitor.

01 var arg = prompt( "Введите arg?" )
02 switch (arg) {
03    case '0' :
04    case '1' :
05      alert( 'Один или ноль' );
06
07    case '2' :
08      alert( 'Два' );
09      break ;
10
11    case 3:
12      alert( 'Никогда не выполнится' );
13
14    case null :
15      alert( 'Отмена' );
16      break ;
17
18    default :
19      alert( 'Неизвестное значение: ' + arg)
20 }

What will it display when entering numbers 0, 1, 2, 3? Think and read on ...

  • If you enter 0 or 1 first alert will be executed, then the execution will continue down to the first break and output the second alert('Два') .
  • If you enter 2 , switch goes to case '2' and prints Два .
  • When you enter 3 , switch switches to default . This is because the prompt returns the string '3' , not a number. Types are different. Switch uses strict equality === , so there will be no coincidence.
  • When canceled, case null will work.

Importance: 4

Rewrite the code using the same switch construction:

01 var a = +prompt( 'a?' , '' );
02
03 if (a == 0) {
04    alert(0);
05 }
06 if (a == 1) {
07    alert(1);
08 }
09
10 if (a == 2 || a == 3) {
11    alert( '2,3' );
12 }

Decision

The first two checks are the usual case , the third is divided into two case :

01 var a = +prompt( 'a?' , '' );
02
03 switch (a) {
04    case 0:
05      alert(0);
06      break ;
07
08    case 1:
09      alert(1);
10      break ;
11
12    case 2:
13    case 3:
14      alert( '2,3' );
15      break ;
16 }

Pay attention: break below is not obligatory, but is set according to the “rules of good form”.

If it is not worth it, then when adding a new case to the end, for example case 4 , we will most likely forget to put it. As a result, the execution of case 2 / case 3 will continue on case 4 and there will be an error.

created: 2014-10-07
updated: 2021-03-13
132522



Rating 9 of 10. count vote: 2
Are you satisfied?:



Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Scripting client side JavaScript, jqvery, BackBone

Terms: Scripting client side JavaScript, jqvery, BackBone