Skip to content

The "switch" statement #300

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 1 commit into from
Jul 15, 2020
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
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:
Las primeras dos validaciones se vuelven dos`case`. La tercera validación se separa en dos casos:

```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.
Nota: El `break` al final no es requerido. Pero lo agregamos para preparar el código para el futuro.

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.
En el futuro existe una probabilidad de que querramos agregar un `case` adicional, por ejemplo `case 4`. Y si olvidamos agregar un break antes, al final de `case 3`, habrá un error. Por tanto, es una forma de auto-asegurarse.
113 changes: 57 additions & 56 deletions 1-js/02-first-steps/14-switch/article.md
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
# The "switch" statement
# La sentencia "switch"

A `switch` statement can replace multiple `if` checks.
Una sentencia `switch` puede reemplazar múltiples condiciones `if`.

It gives a more descriptive way to compare a value with multiple variants.
Provee una mejor manera de comparar un valor con sus múltiples variantes.

## The syntax
## La sintaxis

The `switch` has one or more `case` blocks and an optional default.
`switch` tiene uno o mas bloques `case`y un opcional `default`.

It looks like this:
Se ve de esta forma:

```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).
- El valor de `x` es comparado contra el valor del primer `case` (en este caso, `valor1`), luego contra el segundo (`valor2`) y así sucesivamente, todo esto bajo una igualdad estricta.
- Si la igualdad es encontrada, `switch` empieza a ejecutar el código iniciando por el primer `case` correspondiente, hasta el `break` más cercano (o hasta el final del `switch`).
- Si no se cumple ningún caso entonces el código `default` es ejecutado (si existe).

## An example
## Ejemplo

An example of `switch` (the executed code is highlighted):
Un ejemplo de `switch` (se resalta el código ejecutado):

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

switch (a) {
case 3:
alert( 'Too small' );
alert( 'Muy pequeño' );
break;
*!*
case 4:
alert( 'Exactly!' );
alert( '¡Exacto!' );
break;
*/!*
case 5:
alert( 'Too large' );
alert( 'Muy grande' );
break;
default:
alert( "I don't know such values" );
alert( "Desconozco estos valores" );
}
```

Here the `switch` starts to compare `a` from the first `case` variant that is `3`. The match fails.
Aquí el `switch` inicia comparando `a` con la primera variante `case` que es `3`. La comparación falla.

Then `4`. That's a match, so the execution starts from `case 4` until the nearest `break`.
Luego `4`. La comparación es exitosa, por tanto la ejecución empieza desde `case 4` hasta el `break` más cercano.

**If there is no `break` then the execution continues with the next `case` without any checks.**
**Si no existe `break` entonces la ejecución continúa con el próximo `case` sin ninguna revisión.**

An example without `break`:
Un ejemplo sin `break`:

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

switch (a) {
case 3:
alert( 'Too small' );
alert( 'Muy pequeño' );
*!*
case 4:
alert( 'Exactly!' );
alert( '¡Exacto!' );
case 5:
alert( 'Too big' );
alert( 'Muy grande' );
default:
alert( "I don't know such values" );
alert( "Desconozco estos valores" );
*/!*
}
```

In the example above we'll see sequential execution of three `alert`s:
En el ejemplo anterior veremos ejecuciones de tres `alert` secuenciales:

```js
alert( 'Exactly!' );
alert( 'Too big' );
alert( "I don't know such values" );
alert( '¡Exacto!' );
alert( 'Muy grande' );
alert( "Desconozco estos valores" );
```

````smart header="Any expression can be a `switch/case` argument"
Both `switch` and `case` allow arbitrary expressions.
````encabezado inteligente="Cualquier expresión puede ser un argumento `switch/case`"
Ambos `switch` y `case` permiten expresiones arbitrarias.

For example:
Por ejemplo:

```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("esto se ejecuta, porque +a es 1, exactamente igual b+1");
break;
*/!*

default:
alert("this doesn't run");
alert("esto no se ejecuta");
}
```
Here `+a` gives `1`, that's compared with `b + 1` in `case`, and the corresponding code is executed.
Aquí `+a` da `1`, esto es comparado con `b + 1` en `case`, y el código correspondiente es ejecutado.
````

## Grouping of "case"
## Agrupamiento de "case"

Several variants of `case` which share the same code can be grouped.
Varias variantes de `case` los cuales comparten el mismo código pueden ser agrupadas.

For example, if we want the same code to run for `case 3` and `case 5`:
Por ejemplo, si queremos que se ejecute el mismo código para `case 3` y `case 5`:

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

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

*!*
case 3: // (*) grouped two cases
case 3: // (*) agrupando dos cases
case 5:
alert('Wrong!');
alert("Why don't you take a math class?");
alert('¡Incorrecto!');
alert("¿Por qué no tomas una clase de matemáticas?");
break;
*/!*

default:
alert('The result is strange. Really.');
alert('El resultado es extraño. Realmente.');
}
```

Now both `3` and `5` show the same message.
Ahora ambos `3` y `5` muestran el mismo mensaje.

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`.
La habilidad para "agrupar" cases es un efecto secundario de como trabaja `switch/case` sin `break`. Aquí la ejecución de `case 3` inicia desde la línea `(*)` y continúa a través de `case 5`, porque no existe `break`.

## Type matters
## El tipo importa

Let's emphasize that the equality check is always strict. The values must be of the same type to match.
Vamos a enfatizar que la comparación de igualdad es siempre estricta. Los valores deben ser del mismo tipo para coincidir.

For example, let's consider the code:
Por ejemplo, consideremos el código:

```js run
let arg = prompt("Enter a value?");
let arg = prompt("Ingrese un valor");
switch (arg) {
case '0':
case '1':
alert( 'One or zero' );
alert( 'Uno o cero' );
break;

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

case 3:
alert( 'Never executes!' );
alert( '¡Nunca ejecuta!' );
break;
default:
alert( 'An unknown value' );
alert( 'Un valor desconocido' );
}
```

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`, se ejecuta el primer `alert`.
2. Para `2` se ejecuta el segundo `alert`.
3. Pero para `3`, el resultado del `prompt` es un string `"3"`, el cual no es estrictamente igual `===` al número `3`. Por tanto ¡Tenemos un código muerto en `case 3`! La variante `default` se ejecutará.