Skip to content

Commit 9577373

Browse files
authored
Merge pull request #57 from tikoflano/master
Type Conversions
2 parents 56bcb6b + 6dcbeeb commit 9577373

File tree

3 files changed

+67
-69
lines changed

3 files changed

+67
-69
lines changed

1-js/02-first-steps/06-type-conversions/1-primitive-conversions-questions/solution.md

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,9 @@ null + 1 = 1 // (5)
1616
undefined + 1 = NaN // (6)
1717
```
1818

19-
1. The addition with a string `"" + 1` converts `1` to a string: `"" + 1 = "1"`, and then we have `"1" + 0`, the same rule is applied.
20-
2. The subtraction `-` (like most math operations) only works with numbers, it converts an empty string `""` to `0`.
21-
3. The addition with a string appends the number `5` to the string.
22-
4. The subtraction always converts to numbers, so it makes `" -9 "` a number `-9` (ignoring spaces around it).
23-
5. `null` becomes `0` after the numeric conversion.
24-
6. `undefined` becomes `NaN` after the numeric conversion.
19+
1. La suma con un string `"" + 1` convierte el número `1` a un string: `"" + 1 = "1"`, luego tenemos `"1" + 0`, la misma regla es aplicada.
20+
2. La resta `-` (como la mayoría de las operaciones matemáticas) sólo funciona con números, convierte un string vacío `""` a `0`.
21+
3. La suma con un string añade el número `5` al string.
22+
4. La resta siempre convierte a números, por lo que convierte `" -9 "` al número `-9` (ignorando los espacios alrededor del string).
23+
5. La conversión a número convierete `null` en `0`.
24+
6. La conversión a número convierete `undefined` en `NaN`.

1-js/02-first-steps/06-type-conversions/1-primitive-conversions-questions/task.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
importance: 5
1+
importancia: 5
22

33
---
44

5-
# Type conversions
5+
# Conversiones de Tipos
66

7-
What are results of these expressions?
7+
¿Cuáles son los resultados de estas expresiones?
88

99
```js no-beautify
1010
"" + 1 + 0
@@ -23,4 +23,4 @@ null + 1
2323
undefined + 1
2424
```
2525

26-
Think well, write down and then compare with the answer.
26+
Piensa cuidadosamente, luego escribe los resultados y compáralos con la respuesta.
Lines changed: 57 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -1,160 +1,158 @@
1-
# Type Conversions
1+
# Conversiones de Tipos
22

3-
Most of the time, operators and functions automatically convert the values given to them to the right type. This is called "type conversion".
3+
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".
44

5-
For example, `alert` automatically converts any value to a string to show it. Mathematical operations convert values to numbers.
5+
Por ejemplo, `alert` convierte automáticamente cualquier valor a string para mostrarlo. Las operaciones matemáticas convierten los valores a números.
66

7-
There are also cases when we need to explicitly convert a value to the expected type.
7+
También hay casos donde necesitamos convertir de manera explícita un valor al tipo esperado.
88

9-
```smart header="Not talking about objects yet"
10-
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>.
9+
```smart header="Aún no hablamos de objetos"
10+
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>.
1111
```
1212

1313
## ToString
1414

15-
String conversion happens when we need the string form of a value.
15+
La conversión a string ocurre cuando necesitamos la representación en forma de texto de un valor.
1616

17-
For example, `alert(value)` does it to show the value.
17+
Por ejemplo, `alert(value)` lo hace para mostrar el valor como texto.
1818

19-
We can also call the `String(value)` function to convert a value to a string:
19+
También podemos llamar a la función `String(value)` para convertir un valor a string:
2020

2121
```js run
2222
let value = true;
2323
alert(typeof value); // boolean
2424

2525
*!*
26-
value = String(value); // now value is a string "true"
26+
value = String(value); // ahora value es el string "true"
2727
alert(typeof value); // string
2828
*/!*
2929
```
3030

31-
String conversion is mostly obvious. A `false` becomes `"false"`, `null` becomes `"null"`, etc.
31+
La conversión a string es bastante obvia. El boolean `false` se convierte en `"false"`, `null` en `"null"`, etc.
3232

3333
## ToNumber
3434

35-
Numeric conversion happens in mathematical functions and expressions automatically.
35+
La conversión numérica ocurre automáticamente en funciones matemáticas y expresiones.
3636

37-
For example, when division `/` is applied to non-numbers:
37+
Por ejemplo, cuando se dividen valores no numéricos usando `/`:
3838

3939
```js run
40-
alert( "6" / "2" ); // 3, strings are converted to numbers
40+
alert( "6" / "2" ); // 3, los strings son convertidos a números
4141
```
42-
43-
We can use the `Number(value)` function to explicitly convert a `value` to a number:
42+
Podemos usar la función `Number(value)` para convertir de forma explícita un valor a un número:
4443

4544
```js run
4645
let str = "123";
4746
alert(typeof str); // string
4847

49-
let num = Number(str); // becomes a number 123
48+
let num = Number(str); // se convierte en 123
5049

5150
alert(typeof num); // number
5251
```
52+
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.
5353

54-
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.
55-
56-
If the string is not a valid number, the result of such a conversion is `NaN`. For instance:
54+
Si el string no es un número válido, el resultado de la conversión será `NaN`. Por ejemplo:
5755

5856
```js run
59-
let age = Number("an arbitrary string instead of a number");
57+
let age = Number("un texto arbitrario en vez de un número");
6058

61-
alert(age); // NaN, conversion failed
59+
alert(age); // NaN, conversión fallida
6260
```
6361

64-
Numeric conversion rules:
62+
Reglas de conversión numérica:
6563

66-
| Value | Becomes... |
64+
| Valor | Se convierte en... |
6765
|-------|-------------|
6866
|`undefined`|`NaN`|
6967
|`null`|`0`|
70-
|<code>true&nbsp;and&nbsp;false</code> | `1` and `0` |
71-
| `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`. |
68+
|<code>true&nbsp;and&nbsp;false</code> | `1` y `0` |
69+
| `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`. |
7270

7371
Examples:
7472

7573
```js run
7674
alert( Number(" 123 ") ); // 123
77-
alert( Number("123z") ); // NaN (error reading a number at "z")
75+
alert( Number("123z") ); // NaN (error al leer un número en "z")
7876
alert( Number(true) ); // 1
7977
alert( Number(false) ); // 0
8078
```
8179

82-
Please note that `null` and `undefined` behave differently here: `null` becomes zero while `undefined` becomes `NaN`.
80+
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`.
8381

84-
````smart header="Addition '+' concatenates strings"
85-
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.
82+
````smart header="Adición '+' concatena strings"
83+
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.
8684
87-
Then, it concatenates (joins) them:
85+
Luego, los concatena (une):
8886
8987
```js run
90-
alert( 1 + '2' ); // '12' (string to the right)
91-
alert( '1' + 2 ); // '12' (string to the left)
88+
alert( 1 + '2' ); // '12' (string a la derecha)
89+
alert( '1' + 2 ); // '12' (string a la izqueirda)
9290
```
9391
94-
This only happens when at least one of the arguments is a string. Otherwise, values are converted to numbers.
92+
Esto ocurre solo si al menos uno de los argumentos es un string, en caso contario los valores son convertidos a número.
9593
````
9694

9795
## ToBoolean
9896

99-
Boolean conversion is the simplest one.
97+
La conversión a boolean es la más simple.
10098

101-
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)`.
99+
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)`.
102100

103-
The conversion rule:
101+
Las reglas de conversión:
104102

105-
- Values that are intuitively "empty", like `0`, an empty string, `null`, `undefined`, and `NaN`, become `false`.
106-
- Other values become `true`.
103+
- Los valores que son intuitivamente "vacíos", como `0`, `""`, `null`, `undefined`, y `NaN`, se convierten en `false`.
104+
- Otros valores se convierten en `true`.
107105

108-
For instance:
106+
Por ejemplo:
109107

110108
```js run
111109
alert( Boolean(1) ); // true
112110
alert( Boolean(0) ); // false
113111

114-
alert( Boolean("hello") ); // true
112+
alert( Boolean("hola") ); // true
115113
alert( Boolean("") ); // false
116114
```
117115

118-
````warn header="Please note: the string with zero `\"0\"` is `true`"
119-
Some languages (namely PHP) treat `"0"` as `false`. But in JavaScript, a non-empty string is always `true`.
116+
````warn header="Ten en cuenta: el string con un cero `\"0\"` es `true`"
117+
Algunos lenguajes (como PHP) tratan `"0"` como `false`. Pero en JavaScript, un string no vacío es siempre `true`.
120118

121119
```js run
122120
alert( Boolean("0") ); // true
123-
alert( Boolean(" ") ); // spaces, also true (any non-empty string is true)
121+
alert( Boolean(" ") ); // sólo espacios, también true (cualquier string no vacío es true)
124122
```
125123
````
126124
127125
128-
## Summary
126+
## Resumen
129127
130-
The three most widely used type conversions are to string, to number, and to boolean.
128+
Las tres conversiones de tipo más usadas son a string, a número y a boolean.
131129
132-
**`ToString`** -- Occurs when we output something. Can be performed with `String(value)`. The conversion to string is usually obvious for primitive values.
130+
**`ToString`** -- Ocurre cuando se muestra algo. Se puede realizar con `String(value)`. La conversión a string es usualmente obvia para los valores primitivos.
133131
134-
**`ToNumber`** -- Occurs in math operations. Can be performed with `Number(value)`.
132+
**`ToNumber`** -- Ocurre en operaciones matemáticas. Se puede realizar con `Number(value)`.
135133
136-
The conversion follows the rules:
134+
La conversión sigue las reglas:
137135
138-
| Value | Becomes... |
136+
| Valor | Se convierte en... |
139137
|-------|-------------|
140138
|`undefined`|`NaN`|
141139
|`null`|`0`|
142140
|<code>true&nbsp;/&nbsp;false</code> | `1 / 0` |
143-
| `string` | The string is read "as is", whitespaces from both sides are ignored. An empty string becomes `0`. An error gives `NaN`. |
141+
| `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`. |
144142
145-
**`ToBoolean`** -- Occurs in logical operations. Can be performed with `Boolean(value)`.
143+
**`ToBoolean`** -- Ocurren en operaciones lógicas. Se puede realizar con `Boolean(value)`.
146144
147-
Follows the rules:
145+
Sigue las reglas:
148146
149-
| Value | Becomes... |
147+
| Valor | Se convierte en... |
150148
|-------|-------------|
151149
|`0`, `null`, `undefined`, `NaN`, `""` |`false`|
152-
|any other value| `true` |
150+
|cualquier otro valor| `true` |
153151
154152
155-
Most of these rules are easy to understand and memorize. The notable exceptions where people usually make mistakes are:
153+
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:
156154
157-
- `undefined` is `NaN` as a number, not `0`.
158-
- `"0"` and space-only strings like `" "` are true as a boolean.
155+
- `undefined` es `NaN` como número, no `0`.
156+
- `"0"` y textos que solo contienen espacios como `" "` son `true` como boolean.
159157
160-
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.
158+
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.

0 commit comments

Comments
 (0)