Skip to content
Merged
Changes from 1 commit
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
110 changes: 54 additions & 56 deletions 1-js/02-first-steps/06-type-conversions/article.md
Original file line number Diff line number Diff line change
@@ -1,74 +1,72 @@
# 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.
Tmabién hay casos donde necesitamos convertir de manera explícita un valor al tipo esperado.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

También

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems you reviewed the wrong commit. That was fixed in the latest one.

I will update this PR with the translation of task and solution.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@tikoflano It keeps showing "Tmabién" and other comments. Can you confirm that you updated the parts I commented you about?


```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 como 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(valor)` 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 la función `String(valor)` 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 conversion 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áldio, el resultado de la comversión será `NaN`. Por ejemplo:

```js run
let age = Number("an arbitrary string instead of a number");

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&nbsp;and&nbsp;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`. |
| `string` | Se eliminan los espacios al inicio y final del texto. Si el string resultante es vacío, el resultado es `0`. Sino el número es "leído" del string. Un error devuelve `NaN`. |

Examples:

Expand All @@ -79,82 +77,82 @@ alert( Number(true) ); // 1
alert( Number(false) ); // 0
```

Please note that `null` and `undefined` behave differently here: `null` becomes zero while `undefined` becomes `NaN`.
Tomar en cuenta que `null` y `undefined` se comportan distinto 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 operadores es un string. Sino, 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="Tomar 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&nbsp;/&nbsp;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ácil 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.
Copy link
Collaborator

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

Copy link
Contributor Author

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.


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.