- Notifications
You must be signed in to change notification settings - Fork230
Patch 1#299
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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
Closed
Uh oh!
There was an error while loading.Please reload this page.
Closed
Patch 1#299
Changes fromall commits
Commits
Show all changes
5 commits Select commitHold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
172 changes: 0 additions & 172 deletions1-js/02-first-steps/13-switch/article.md
This file was deleted.
Oops, something went wrong.
Uh oh!
There was an error while loading.Please reload this page.
174 changes: 174 additions & 0 deletions1-js/02-first-steps/14-switch/article.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,174 @@ | ||
| # La sentencia "switch" | ||
| Una sentencia `switch` puede reemplazar múltiples condiciones `if`. | ||
| Provee una mejor manera de comparar un valor con sus múltiples variantes. | ||
| ## La sintaxis | ||
| `switch` tiene uno o mas bloques `case`y un opcional `default`. | ||
| Se ve de esta forma: | ||
| ```js no-beautify | ||
| switch(x) { | ||
| case 'valor1': // if (x === 'valor1') | ||
| ... | ||
| [break] | ||
| case 'valor2': // if (x === 'valor2') | ||
| ... | ||
| [break] | ||
| default: | ||
| ... | ||
| [break] | ||
| } | ||
| ``` | ||
| - 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). | ||
| ## Ejemplo | ||
| Un ejemplo de `switch` (se resalta el código ejecutado): | ||
| ```js run | ||
| let a = 2 + 2; | ||
| switch (a) { | ||
| case 3: | ||
| alert( 'Muy pequeño' ); | ||
| break; | ||
| *!* | ||
| case 4: | ||
| alert( '¡Exacto!' ); | ||
| break; | ||
| */!* | ||
| case 5: | ||
| alert( 'Muy grande' ); | ||
| break; | ||
| default: | ||
| alert( "Desconozco estos valores" ); | ||
| } | ||
| ``` | ||
| Aquí el `switch` inicia comparando `a` con la primera variante `case` que es `3`. La comparación falla. | ||
| Luego `4`. La comparación es exitosa, por tanto la ejecución empieza desde `case 4` hasta el `break` más cercano. | ||
| **Si no existe `break` entonces la ejecución continúa con el próximo `case` sin ninguna revisión.** | ||
| Un ejemplo sin `break`: | ||
| ```js run | ||
| let a = 2 + 2; | ||
| switch (a) { | ||
| case 3: | ||
| alert( 'Muy pequeño' ); | ||
| *!* | ||
| case 4: | ||
| alert( '¡Exacto!' ); | ||
| case 5: | ||
| alert( 'Muy grande' ); | ||
| default: | ||
| alert( "Desconozco estos valores" ); | ||
| */!* | ||
| } | ||
| ``` | ||
| En el ejemplo anterior veremos ejecuciones de tres `alert` secuenciales: | ||
| ```js | ||
| alert( '¡Exacto!' ); | ||
| alert( 'Muy grande' ); | ||
| alert( "Desconozco estos valores" ); | ||
| ``` | ||
| ````encabezado inteligente="Cualquier expresión puede ser un argumento `switch/case`" | ||
| Ambos `switch` y `case` permiten expresiones arbitrarias. | ||
| Por ejemplo: | ||
| ```js run | ||
| let a = "1"; | ||
| let b = 0; | ||
| switch (+a) { | ||
| *!* | ||
| case b + 1: | ||
| alert("esto se ejecuta, porque +a es 1, exactamente igual b+1"); | ||
| break; | ||
| */!* | ||
| default: | ||
| alert("esto no se ejecuta"); | ||
| } | ||
| ``` | ||
| Aquí `+a` da `1`, esto es comparado con `b + 1` en `case`, y el código correspondiente es ejecutado. | ||
| ```` | ||
| ## Agrupamiento de "case" | ||
| Varias variantes de `case` los cuales comparten el mismo código pueden ser agrupadas. | ||
| 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('¡Correcto!'); | ||
| break; | ||
| *!* | ||
| case 3: // (*) agrupando dos cases | ||
| case 5: | ||
| alert('¡Incorrecto!'); | ||
| alert("¿Por qué no tomas una clase de matemáticas?"); | ||
| break; | ||
| */!* | ||
| default: | ||
| alert('El resultado es extraño. Realmente.'); | ||
| } | ||
| ``` | ||
| Ahora ambos `3` y `5` muestran el mismo mensaje. | ||
| 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`. | ||
| ## El tipo importa | ||
| Vamos a enfatizar que la comparación de igualdad es siempre estricta. Los valores deben ser del mismo tipo para coincidir. | ||
| Por ejemplo, consideremos el código: | ||
| ```js run | ||
| let arg = prompt("Ingrese un valor"); | ||
| switch (arg) { | ||
| case '0': | ||
| case '1': | ||
| alert( 'Uno o cero' ); | ||
| break; | ||
| case '2': | ||
| alert( 'Dos' ); | ||
| break; | ||
| case 3: | ||
| alert( '¡Nunca ejecuta!' ); | ||
| break; | ||
| default: | ||
| alert( 'Un valor desconocido' ); | ||
| } | ||
| ``` | ||
| 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á. | ||
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.