-
Notifications
You must be signed in to change notification settings - Fork 229
Type Conversions #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
Type Conversions #57
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
f976410
Update article.md
tikoflano 773a22a
Corrección de errores menores
tikoflano 9ff5db7
Task translation
tikoflano 9ec05fa
Solutions translation
tikoflano 8a6090c
Typo fixes
tikoflano 844b8d7
Update article.md
tikoflano a2e6ebe
Update article.md
tikoflano 6dcbeeb
Typo fix
tikoflano File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
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 |
---|---|---|
@@ -1,160 +1,158 @@ | ||
# Type Conversions | ||
# Conversiones de Tipos | ||
|
||
Most of the time, operators and functions automatically convert the values given to them to the right type. This is called "type conversion". | ||
La mayoría de las veces, los operadores y funciones convierten automáticamente los valores que se les pasan al tipo correcto. Esto es llamado "conversión de tipo". | ||
|
||
For example, `alert` automatically converts any value to a string to show it. Mathematical operations convert values to numbers. | ||
Por ejemplo, `alert` convierte automáticamente cualquier valor a string para mostrarlo. Las operaciones matemáticas convierten los valores a números. | ||
|
||
There are also cases when we need to explicitly convert a value to the expected type. | ||
También hay casos donde necesitamos convertir de manera explícita un valor al tipo esperado. | ||
|
||
```smart header="Not talking about objects yet" | ||
In this chapter, we won't cover objects. Instead, we'll study primitives first. Later, after we learn about objects, we'll see how object conversion works in the chapter <info:object-toprimitive>. | ||
```smart header="Aún no hablamos de objetos" | ||
En este capítulo no cubriremos los objetos. Estudiaremos los valores primitivos primero. Luego, después de haber hablado sobre objetos, veremos cómo funciona la conversión de objetos en este capítulo <info:object-toprimitive>. | ||
``` | ||
|
||
## ToString | ||
|
||
String conversion happens when we need the string form of a value. | ||
La conversión a string ocurre cuando necesitamos la representación en forma de texto de un valor. | ||
|
||
For example, `alert(value)` does it to show the value. | ||
Por ejemplo, `alert(value)` lo hace para mostrar el valor como texto. | ||
|
||
We can also call the `String(value)` function to convert a value to a string: | ||
También podemos llamar a la función `String(value)` para convertir un valor a string: | ||
|
||
```js run | ||
let value = true; | ||
alert(typeof value); // boolean | ||
|
||
*!* | ||
value = String(value); // now value is a string "true" | ||
value = String(value); // ahora value es el string "true" | ||
alert(typeof value); // string | ||
*/!* | ||
``` | ||
|
||
String conversion is mostly obvious. A `false` becomes `"false"`, `null` becomes `"null"`, etc. | ||
La conversión a string es bastante obvia. El boolean `false` se convierte en `"false"`, `null` en `"null"`, etc. | ||
|
||
## ToNumber | ||
|
||
Numeric conversion happens in mathematical functions and expressions automatically. | ||
La conversión numérica ocurre automáticamente en funciones matemáticas y expresiones. | ||
|
||
For example, when division `/` is applied to non-numbers: | ||
Por ejemplo, cuando se dividen valores no numéricos usando `/`: | ||
|
||
```js run | ||
alert( "6" / "2" ); // 3, strings are converted to numbers | ||
alert( "6" / "2" ); // 3, los strings son convertidos a números | ||
``` | ||
|
||
We can use the `Number(value)` function to explicitly convert a `value` to a number: | ||
Podemos usar la función `Number(value)` para convertir de forma explícita un valor a un número: | ||
|
||
```js run | ||
let str = "123"; | ||
alert(typeof str); // string | ||
|
||
let num = Number(str); // becomes a number 123 | ||
let num = Number(str); // se convierte en 123 | ||
|
||
alert(typeof num); // number | ||
``` | ||
La conversión explícita es requerida usualmente cuando leemos un valor desde una fuente basada en texto, como lo son los campos de texto en los formularios, pero que esperamos que contengan un valor numérico. | ||
|
||
Explicit conversion is usually required when we read a value from a string-based source like a text form but expect a number to be entered. | ||
|
||
If the string is not a valid number, the result of such a conversion is `NaN`. For instance: | ||
Si el string no es un número válido, el resultado de la conversión será `NaN`. Por ejemplo: | ||
|
||
```js run | ||
let age = Number("an arbitrary string instead of a number"); | ||
let age = Number("un texto arbitrario en vez de un número"); | ||
|
||
alert(age); // NaN, conversion failed | ||
alert(age); // NaN, conversión fallida | ||
``` | ||
|
||
Numeric conversion rules: | ||
Reglas de conversión numérica: | ||
|
||
| Value | Becomes... | | ||
| Valor | Se convierte en... | | ||
|-------|-------------| | ||
|`undefined`|`NaN`| | ||
|`null`|`0`| | ||
|<code>true and false</code> | `1` and `0` | | ||
| `string` | Whitespaces from the start and end are removed. If the remaining string is empty, the result is `0`. Otherwise, the number is "read" from the string. An error gives `NaN`. | | ||
|<code>true and false</code> | `1` y `0` | | ||
| `string` | Se eliminan los espacios al inicio y final del texto. Si el string resultante es vacío, el resultado es `0`, en caso contario el número es "leído" del string. Un error devuelve `NaN`. | | ||
|
||
Examples: | ||
|
||
```js run | ||
alert( Number(" 123 ") ); // 123 | ||
alert( Number("123z") ); // NaN (error reading a number at "z") | ||
alert( Number("123z") ); // NaN (error al leer un número en "z") | ||
alert( Number(true) ); // 1 | ||
alert( Number(false) ); // 0 | ||
``` | ||
|
||
Please note that `null` and `undefined` behave differently here: `null` becomes zero while `undefined` becomes `NaN`. | ||
Ten en cuenta que `null` y `undefined` se comportan de distinta manera aquí: `null` se convierte en `0` mientras que `undefined` se convierte en `NaN`. | ||
|
||
````smart header="Addition '+' concatenates strings" | ||
Almost all mathematical operations convert values to numbers. A notable exception is addition `+`. If one of the added values is a string, the other one is also converted to a string. | ||
````smart header="Adición '+' concatena strings" | ||
Casi todas las operaciones matemáticas convierten valores a números. Una excepción notable es la suma `+`. Si uno de los valores sumados es un string, el otro valor es convertido a string. | ||
|
||
Then, it concatenates (joins) them: | ||
Luego, los concatena (une): | ||
|
||
```js run | ||
alert( 1 + '2' ); // '12' (string to the right) | ||
alert( '1' + 2 ); // '12' (string to the left) | ||
alert( 1 + '2' ); // '12' (string a la derecha) | ||
alert( '1' + 2 ); // '12' (string a la izqueirda) | ||
``` | ||
|
||
This only happens when at least one of the arguments is a string. Otherwise, values are converted to numbers. | ||
Esto ocurre solo si al menos uno de los argumentos es un string, en caso contario los valores son convertidos a número. | ||
```` | ||
|
||
## ToBoolean | ||
|
||
Boolean conversion is the simplest one. | ||
La conversión a boolean es la más simple. | ||
|
||
It happens in logical operations (later we'll meet condition tests and other similar things) but can also be performed explicitly with a call to `Boolean(value)`. | ||
Ocurre en operaciones lógicas (más adelante veremos test condicionales y otras cosas similares) pero también puede realizarse de forma explícita llamando a la función `Boolean(value)`. | ||
|
||
The conversion rule: | ||
Las reglas de conversión: | ||
|
||
- Values that are intuitively "empty", like `0`, an empty string, `null`, `undefined`, and `NaN`, become `false`. | ||
- Other values become `true`. | ||
- Los valores que son intuitivamente "vacíos", como `0`, `""`, `null`, `undefined`, y `NaN`, se convierten en `false`. | ||
- Otros valores se convierten en `true`. | ||
|
||
For instance: | ||
Por ejemplo: | ||
|
||
```js run | ||
alert( Boolean(1) ); // true | ||
alert( Boolean(0) ); // false | ||
|
||
alert( Boolean("hello") ); // true | ||
alert( Boolean("hola") ); // true | ||
alert( Boolean("") ); // false | ||
``` | ||
|
||
````warn header="Please note: the string with zero `\"0\"` is `true`" | ||
Some languages (namely PHP) treat `"0"` as `false`. But in JavaScript, a non-empty string is always `true`. | ||
````warn header="Ten en cuenta: el string con un cero `\"0\"` es `true`" | ||
Algunos lenguajes (como PHP) tratan `"0"` como `false`. Pero en JavaScript, un string no vacío es siempre `true`. | ||
|
||
```js run | ||
alert( Boolean("0") ); // true | ||
alert( Boolean(" ") ); // spaces, also true (any non-empty string is true) | ||
alert( Boolean(" ") ); // sólo espacios, también true (cualquier string no vacío es true) | ||
``` | ||
```` | ||
|
||
|
||
## Summary | ||
## Resumen | ||
|
||
The three most widely used type conversions are to string, to number, and to boolean. | ||
Las tres conversiones de tipo más usadas son a string, a número y a boolean. | ||
|
||
**`ToString`** -- Occurs when we output something. Can be performed with `String(value)`. The conversion to string is usually obvious for primitive values. | ||
**`ToString`** -- Ocurre cuando se muestra algo. Se puede realizar con `String(value)`. La conversión a string es usualmente obvia para los valores primitivos. | ||
|
||
**`ToNumber`** -- Occurs in math operations. Can be performed with `Number(value)`. | ||
**`ToNumber`** -- Ocurre en operaciones matemáticas. Se puede realizar con `Number(value)`. | ||
|
||
The conversion follows the rules: | ||
La conversión sigue las reglas: | ||
|
||
| Value | Becomes... | | ||
| Valor | Se convierte en... | | ||
|-------|-------------| | ||
|`undefined`|`NaN`| | ||
|`null`|`0`| | ||
|<code>true / false</code> | `1 / 0` | | ||
| `string` | The string is read "as is", whitespaces from both sides are ignored. An empty string becomes `0`. An error gives `NaN`. | | ||
| `string` | El string es leído "como es", los espacios en blanco tanto al inicio como al final son ignorados. Un string vacío se convierte en `0`. Un error entrega `NaN`. | | ||
|
||
**`ToBoolean`** -- Occurs in logical operations. Can be performed with `Boolean(value)`. | ||
**`ToBoolean`** -- Ocurren en operaciones lógicas. Se puede realizar con `Boolean(value)`. | ||
|
||
Follows the rules: | ||
Sigue las reglas: | ||
|
||
| Value | Becomes... | | ||
| Valor | Se convierte en... | | ||
|-------|-------------| | ||
|`0`, `null`, `undefined`, `NaN`, `""` |`false`| | ||
|any other value| `true` | | ||
|cualquier otro valor| `true` | | ||
|
||
|
||
Most of these rules are easy to understand and memorize. The notable exceptions where people usually make mistakes are: | ||
La mayoría de estas reglas son fáciles de entender y recordar. Las excepciones más notables donde la gente suele cometer errores son: | ||
|
||
- `undefined` is `NaN` as a number, not `0`. | ||
- `"0"` and space-only strings like `" "` are true as a boolean. | ||
- `undefined` es `NaN` como número, no `0`. | ||
- `"0"` y textos que solo contienen espacios como `" "` son `true` como boolean. | ||
|
||
Objects aren't covered here. We'll return to them later in the chapter <info:object-toprimitive> that is devoted exclusively to objects after we learn more basic things about JavaScript. | ||
Los objetos no son cubiertos aquí. Volveremos a ellos más tarde en el capítulo <info:object-toprimitive> que está dedicado exclusivamente a objetos después de que aprendamos más cosas básicas sobre JavaScript. |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Quedaría mejor cadenas en lugar de textos
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
En todo el resto del artículo se usa la palabra "texto". Creo que "cadena" o "cadena de caracteres" puede confundir al lector ya que no se ha explicado lo que es.