Skip to content

The "switch" statement #80

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 21 commits into from
Jul 13, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
3618c1e
1.2.14
otmon76 Apr 18, 2022
689f6ef
Update article.md
otmon76 Jun 27, 2022
46e7da1
Update 1-js/02-first-steps/14-switch/article.md
otmon76 Jul 13, 2022
8267ffd
Update 1-js/02-first-steps/14-switch/article.md
otmon76 Jul 13, 2022
be04a15
Update 1-js/02-first-steps/14-switch/article.md
otmon76 Jul 13, 2022
b43a7f7
Update 1-js/02-first-steps/14-switch/article.md
otmon76 Jul 13, 2022
0175f60
Update 1-js/02-first-steps/14-switch/article.md
otmon76 Jul 13, 2022
f296504
Update 1-js/02-first-steps/14-switch/2-rewrite-if-switch/solution.md
otmon76 Jul 13, 2022
a00b6ea
Update 1-js/02-first-steps/14-switch/2-rewrite-if-switch/solution.md
otmon76 Jul 13, 2022
83c716b
Update 1-js/02-first-steps/14-switch/1-rewrite-switch-if-else/task.md
otmon76 Jul 13, 2022
ec21520
Update 1-js/02-first-steps/14-switch/1-rewrite-switch-if-else/solutio…
otmon76 Jul 13, 2022
ade3e94
Update 1-js/02-first-steps/14-switch/1-rewrite-switch-if-else/solutio…
otmon76 Jul 13, 2022
0118abc
Update 1-js/02-first-steps/14-switch/article.md
otmon76 Jul 13, 2022
df55831
Update 1-js/02-first-steps/14-switch/article.md
otmon76 Jul 13, 2022
8b0a009
Update 1-js/02-first-steps/14-switch/article.md
otmon76 Jul 13, 2022
f2e8640
Update 1-js/02-first-steps/14-switch/article.md
otmon76 Jul 13, 2022
76ffe78
Update 1-js/02-first-steps/14-switch/article.md
otmon76 Jul 13, 2022
a8d1eef
Update 1-js/02-first-steps/14-switch/article.md
otmon76 Jul 13, 2022
bf79758
Update 1-js/02-first-steps/14-switch/article.md
otmon76 Jul 13, 2022
17b7cf7
Update 1-js/02-first-steps/14-switch/article.md
otmon76 Jul 13, 2022
8ee22f1
Merge branch 'master' into 1.2.14
otmon76 Jul 13, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 12 additions & 12 deletions 1-js/02-first-steps/14-switch/1-rewrite-switch-if-else/solution.md
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
To precisely match the functionality of `switch`, the `if` must use a strict comparison `'==='`.
Abychom dosáhli přesné funkcionality příkazu `switch`, musí `if` používat striktní rovnost `'==='`.

For given strings though, a simple `'=='` works too.
V tomto případě však pro zadané řetězce funguje i obyčejné `'=='`.

```js no-beautify
if(browser == 'Edge') {
alert("You've got the Edge!");
} else if (browser == 'Chrome'
|| browser == 'Firefox'
|| browser == 'Safari'
|| browser == 'Opera') {
alert( 'Okay we support these browsers too' );
if(prohlížeč == 'Edge') {
alert("Vy máte Edge!");
} else if (prohlížeč == 'Chrome'
|| prohlížeč == 'Firefox'
|| prohlížeč == 'Safari'
|| prohlížeč == 'Opera') {
alert( 'Dobrá, tyto prohlížeče také podporujeme' );
} else {
alert( 'We hope that this page looks ok!' );
alert( 'Doufáme, že tato stránka vypadá dobře!' );
}
```

Please note: the construct `browser == 'Chrome' || browser == 'Firefox' …` is split into multiple lines for better readability.
Všimněte si, že konstrukce `prohlížeč == 'Chrome' || prohlížeč == 'Firefox' …` je pro lepší čitelnost rozdělena do několika řádků.

But the `switch` construct is still cleaner and more descriptive.
I tak je ovšem konstrukce `switch` jasnější a přehlednější.
12 changes: 6 additions & 6 deletions 1-js/02-first-steps/14-switch/1-rewrite-switch-if-else/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,25 @@ importance: 5

---

# Rewrite the "switch" into an "if"
# Přepište „switch“ na „if“

Write the code using `if..else` which would correspond to the following `switch`:
Přepište tento kód pomocí `if..else`, které nahradí následující `switch`:

```js
switch (browser) {
switch (prohlížeč) {
case 'Edge':
alert( "You've got the Edge!" );
alert( "Vy máte Edge!" );
break;

case 'Chrome':
case 'Firefox':
case 'Safari':
case 'Opera':
alert( 'Okay we support these browsers too' );
alert( 'Dobrá, tyto prohlížeče také podporujeme' );
break;

default:
alert( 'We hope that this page looks ok!' );
alert( 'Doufáme, že tato stránka vypadá dobře!' );
}
```

6 changes: 3 additions & 3 deletions 1-js/02-first-steps/14-switch/2-rewrite-if-switch/solution.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
The first two checks turn into two `case`. The third check is split into two cases:
První dvě podmínky se dají napsat každá pomocí jednoho `case`, třetí musíme rozdělit do dvou `case`:

```js run
let a = +prompt('a?', '');
Expand All @@ -21,6 +21,6 @@ switch (a) {
}
```

Please note: the `break` at the bottom is not required. But we put it to make the code future-proof.
Všimněte si, že `break` na konci není nezbytný, ale vložili jsme ho, aby bylo lépe možné kód v budoucnu rozšiřovat.

In the future, there is a chance that we'd want to add one more `case`, for example `case 4`. And if we forget to add a break before it, at the end of `case 3`, there will be an error. So that's a kind of self-insurance.
Je možné, že v budoucnu budeme chtít přidat další `case`, například `case 4`. Kdybychom před něj na konec `case 3` zapomněli umístit `break`, nastala by chyba. Je to tedy určitý druh pojistky.
4 changes: 2 additions & 2 deletions 1-js/02-first-steps/14-switch/2-rewrite-if-switch/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ importance: 4

---

# Rewrite "if" into "switch"
# Přepište „if“ na „switch

Rewrite the code below using a single `switch` statement:
Přepište uvedený kód pomocí jediného příkazu `switch`:

```js run
let a = +prompt('a?', '');
Expand Down
112 changes: 55 additions & 57 deletions 1-js/02-first-steps/14-switch/article.md
Original file line number Diff line number Diff line change
@@ -1,22 +1,20 @@
# The "switch" statement
# Příkaz „switch

A `switch` statement can replace multiple `if` checks.
Příkaz `switch` dokáže nahradit několik podmíněných příkazů `if`. Poskytuje přehlednější způsob, jak porovnat hodnotu s několika variantami.

It gives a more descriptive way to compare a value with multiple variants.
## Syntaxe

## The syntax
Příkaz `switch` obsahuje jeden nebo více bloků `case` a nepovinný blok `default`.

The `switch` has one or more `case` blocks and an optional default.

It looks like this:
Vypadá takto:

```js no-beautify
switch(x) {
case 'value1': // if (x === 'value1')
case 'hodnota1': // if (x === 'hodnota1')
...
[break]

case 'value2': // if (x === 'value2')
case 'hodnota2': // if (x === 'hodnota2')
...
[break]

Expand All @@ -26,71 +24,71 @@ switch(x) {
}
```

- The value of `x` is checked for a strict equality to the value from the first `case` (that is, `value1`) then to the second (`value2`) and so on.
- If the equality is found, `switch` starts to execute the code starting from the corresponding `case`, until the nearest `break` (or until the end of `switch`).
- If no case is matched then the `default` code is executed (if it exists).
- Je ověřena striktní rovnost hodnoty `x` s hodnotou z prvního `case` (tj. `hodnota1`), pak s druhou `hodnota2`, a tak dále.
- Pokud je rovnost nalezena, `switch` začne vykonávat kód od odpovídajícího `case` až do nejbližšího `break` (nebo do konce `switch`).
- Není-li nalezena žádná rovnost, je vykonán kód `default` (pokud je uveden).

## An example
## Příklad

An example of `switch` (the executed code is highlighted):
Příklad příkazu `switch` (vykonaný kód je zvýrazněn):

```js run
let a = 2 + 2;

switch (a) {
case 3:
alert( 'Too small' );
alert( 'Příliš málo' );
break;
*!*
case 4:
alert( 'Exactly!' );
alert( 'Přesně!' );
break;
*/!*
case 5:
alert( 'Too big' );
alert( 'Příliš mnoho' );
break;
default:
alert( "I don't know such values" );
alert( "Takové hodnoty neznám" );
}
```

Here the `switch` starts to compare `a` from the first `case` variant that is `3`. The match fails.
Zde `switch` začne porovnávat `a` od první varianty `case`, kterou je `3`. Porovnání neuspěje.

Then `4`. That's a match, so the execution starts from `case 4` until the nearest `break`.
Pak `4`. Tady je nalezena shoda, takže výkon začne od `case 4` a skončí na nejbližším `break`.

**If there is no `break` then the execution continues with the next `case` without any checks.**
**Není-li přítomen příkaz `break`, výkon pokračuje další větví `case` bez jakéhokoli porovnání.**

An example without `break`:
Příklad bez `break`:

```js run
let a = 2 + 2;

switch (a) {
case 3:
alert( 'Too small' );
alert( 'Příliš málo' );
*!*
case 4:
alert( 'Exactly!' );
alert( 'Přesně!' );
case 5:
alert( 'Too big' );
alert( 'Příliš mnoho' );
default:
alert( "I don't know such values" );
alert( "Takové hodnoty neznám" );
*/!*
}
```

In the example above we'll see sequential execution of three `alert`s:
V uvedeném příkladu vidíme sekvenční vykonání tří `alert`ů:

```js
alert( 'Exactly!' );
alert( 'Too big' );
alert( "I don't know such values" );
alert( 'Přesně!' );
alert( 'Příliš mnoho' );
alert( "Takové hodnoty neznám" );
```

````smart header="Any expression can be a `switch/case` argument"
Both `switch` and `case` allow arbitrary expressions.
````smart header="Argumentem `switch/case` může být jakýkoli výraz"
Jak `switch`, tak `case` dovolují libovolné výrazy.

For example:
Příklad:

```js run
let a = "1";
Expand All @@ -99,74 +97,74 @@ let b = 0;
switch (+a) {
*!*
case b + 1:
alert("this runs, because +a is 1, exactly equals b+1");
alert("toto se vykoná, protože +a je 1, což se přesně rovná b+1");
break;
*/!*

default:
alert("this doesn't run");
alert("toto se nevykoná");
}
```
Here `+a` gives `1`, that's compared with `b + 1` in `case`, and the corresponding code is executed.
Zde `+a` dává `1`, to se v `case` porovná s `b + 1` a spustí se příslušný kód.
````

## Grouping of "case"
## Seskupování „case

Several variants of `case` which share the same code can be grouped.
Je možné seskupit několik variant větví `case`, které mají mít stejný kód.

For example, if we want the same code to run for `case 3` and `case 5`:
Například když chceme, aby se stejný kód spustil pro `case 3` a `case 5`:

```js run no-beautify
let a = 3;

switch (a) {
case 4:
alert('Right!');
alert('Správně!');
break;

*!*
case 3: // (*) grouped two cases
case 3: // (*) dvě seskupené větve case
case 5:
alert('Wrong!');
alert("Why don't you take a math class?");
alert('Špatně!');
alert("Proč nenavštěvujete kurz matematiky?");
break;
*/!*

default:
alert('The result is strange. Really.');
alert('Tento výsledek je divný. Opravdu.');
}
```

Now both `3` and `5` show the same message.
Nyní `3` a `5` zobrazí stejnou zprávu.

The ability to "group" cases is a side-effect of how `switch/case` works without `break`. Here the execution of `case 3` starts from the line `(*)` and goes through `case 5`, because there's no `break`.
Schopnost „seskupovat“ větve je vedlejší efekt toho, jak `switch/case` funguje bez `break`. Zde provádění `case 3` začne od řádku `(*)` a projde přes `case 5`, protože tam není žádný `break`.

## Type matters
## Na typu záleží

Let's emphasize that the equality check is always strict. The values must be of the same type to match.
Zdůrazňujeme, že ověření rovnosti je vždy striktní. Aby se hodnoty rovnaly, musejí být stejného typu.

For example, let's consider the code:
Uvažujme například tento kód:

```js run
let arg = prompt("Enter a value?");
let arg = prompt("Zadejte hodnotu");
switch (arg) {
case '0':
case '1':
alert( 'One or zero' );
alert( 'Jedna nebo nula' );
break;

case '2':
alert( 'Two' );
alert( 'Dvě' );
break;

case 3:
alert( 'Never executes!' );
alert( 'Toto se nikdy nevykoná!' );
break;
default:
alert( 'An unknown value' );
alert( 'Neznámá hodnota' );
}
```

1. For `0`, `1`, the first `alert` runs.
2. For `2` the second `alert` runs.
3. But for `3`, the result of the `prompt` is a string `"3"`, which is not strictly equal `===` to the number `3`. So we've got a dead code in `case 3`! The `default` variant will execute.
1. Pro `0` a `1` se spustí první `alert`.
2. Pro `2` se spustí druhý `alert`.
3. Avšak pro `3` je výsledkem příkazu `prompt` řetězec `"3"`, který není striktně roven `===` číslu `3`. Proto jsme pro `case 3` získali mrtvý kód! Spustí se varianta `default`.