Skip to content

The "switch" statement #57

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 3 commits into from
Sep 21, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
113 changes: 57 additions & 56 deletions 1-js/02-first-steps/13-switch/article.md
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
# The "switch" statement
# A instrução "switch"

A `switch` statement can replace multiple `if` checks.
Uma instrução `switch` pode substituir muitas comparações `se`.

It gives a more descriptive way to compare a value with multiple variants.
Ela é uma forma mais descritiva de comparar um valor com múltiplas variantes.

## The syntax
## A sintaxe

The `switch` has one or more `case` blocks and an optional default.
O `switch` tem um ou mais blocos `case` (caso) e um `default` (padrão) opcional.

It looks like this:
Tem uma apresentação similar a:

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

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

Expand All @@ -26,71 +26,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).
- O valor de `x` é comparado por meio de uma igualdade exata ao valor do primeiro `case` (isto é, ao `valor1`), a seguir ao do segundo (`valor2`) e assim sucessivamente.
- Se uma igualdade é encontrada, o `switch` começa a executar o código a partir do início do `case` correspondente, até ao próximo `break` (ou até ao fim do `switch`).
- Se nenhum `case` é equiparado então o código em `default` é executado (se existir).

## An example
## Um exemplo

An example of `switch` (the executed code is highlighted):
Um exemplo de `switch` (o código executado está em destaque):

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

switch (a) {
case 3:
alert( 'Too small' );
alert( 'Muito baixo' );
break;
*!*
case 4:
alert( 'Exactly!' );
alert( 'Exacto!' );
break;
*/!*
case 5:
alert( 'Too large' );
alert( 'Muito alto' );
break;
default:
alert( "I don't know such values" );
alert( "Não conheço tais valores" );
}
```

Here the `switch` starts to compare `a` from the first `case` variant that is `3`. The match fails.
Aqui o `switch` começa por comparar `a` à variante no primeiro `case`, que é `3`. A correspondência falha.

Then `4`. That's a match, so the execution starts from `case 4` until the nearest `break`.
Então a `4`. Existe uma correspondência, e assim a execução começa a partir do `case 4` até ao próximo `break`.

**If there is no `break` then the execution continues with the next `case` without any checks.**
**Se não existir um `break` então a execução continua pelo próximo `case` sem quaisquer verificações.**

An example without `break`:
Um exemplo sem `break`:

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

switch (a) {
case 3:
alert( 'Too small' );
alert( 'Muito baixo' );
*!*
case 4:
alert( 'Exactly!' );
alert( 'Exacto!' );
case 5:
alert( 'Too big' );
alert( 'Muito alto' );
default:
alert( "I don't know such values" );
alert( "Não conheço tais valores" );
*/!*
}
```

In the example above we'll see sequential execution of three `alert`s:
No exemplo acima, vemos uma execução sequential de três `alert`'s:

```js
alert( 'Exactly!' );
alert( 'Too big' );
alert( "I don't know such values" );
alert( 'Exacto!' );
alert( 'Muito alto' );
alert( "Não conheço tais valores" );
```

````smart header="Any expression can be a `switch/case` argument"
Both `switch` and `case` allow arbitrary expressions.
````smart header="Any expression can be a switch/case argument"
Ambos `switch` e `case` permitem expressões arbitrárias.

For example:
Por exemplo:

```js run
let a = "1";
Expand All @@ -99,74 +99,75 @@ let b = 0;
switch (+a) {
*!*
case b + 1:
alert("this runs, because +a is 1, exactly equals b+1");
alert("isto executa, porque +a é 1, e é exatamente igual a b+1");
break;
*/!*

default:
alert("this doesn't run");
alert("isto não executa");
}
```
Here `+a` gives `1`, that's compared with `b + 1` in `case`, and the corresponding code is executed.
Aqui `+a` `1`, o que é comparado a `b + 1` no `case`, e o código correspondente é executado.
````

## Grouping of "case"
## Grupos de "case"

Several variants of `case` which share the same code can be grouped.
Múltiplas variantes de `case` que partihem o mesmo código podem ser agrupadas.

For example, if we want the same code to run for `case 3` and `case 5`:
Por exemplo, se quisermos que o mesmo código corra por `case 3` e `case 5`:

```js run no-beautify
let a = 2 + 2;

switch (a) {
case 4:
alert('Right!');
alert('Certo!');
break;

*!*
case 3: // (*) grouped two cases
case 3: // (*) dois cases agrupados
case 5:
alert('Wrong!');
alert("Why don't you take a math class?");
alert('Errado!');
alert("Porque não tem aulas de matemática?");
break;
*/!*

default:
alert('The result is strange. Really.');
alert('O resultado é stranho. Realmente.');
}
```

Now both `3` and `5` show the same message.
Agora ambos `3` e `5` mostram a mesma mensagem.

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`.
A habilidade para "agrupar" cases é um efeito secundário de como `switch/case` funciona sem `break`. Aqui a execução do `case 3` começa pela linha `(*)` e prossegue pelo `case 5`, por não existir `break`.

## Type matters
## O tipo importa

Let's emphasize that the equality check is always strict. The values must be of the same type to match.
Vamos emfatizar que a verificação da igualdade é sempre exata. Os valores devem também ser do mesmo tipo para existir correspondência.

For example, let's consider the code:
Por exemplo, consideremos o código:

```js run
let arg = prompt("Enter a value?");
let arg = prompt("Insira um valor?");
switch (arg) {
case '0':
case '1':
alert( 'One or zero' );
alert( 'Um ou zero' );
break;

case '2':
alert( 'Two' );
alert( 'Dois' );
break;

case 3:
alert( 'Never executes!' );
alert( 'Nunca executa!' );
break;
default:
alert( 'An unknown value' );
alert( 'Um valor desconhecido' );
}
```

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. Para `0`, `1`, o primeiro `alert` executa.
2. Para `2` o segundo `alert` corre.
3. Mas para `3`, o resultado do `prompt` á a string `"3"`, que não é estritamente igual `===` ao número `3`. Assim temos código não
executável em `case 3`! A variante `default` será executada.
Loading