Skip to content

Commit fcb2bd1

Browse files
author
Márcio Rodrigo
committed
Update type-conversions
1 parent 73b847d commit fcb2bd1

File tree

3 files changed

+73
-73
lines changed

3 files changed

+73
-73
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. A adição com uma string `"" + 1` converte `1` para uma string: `"" + 1 = "1"`, e então temos `"1" + 0`, a mesma regra é aplicada.
20+
2. A subtração `-` (como a maioria das operações matemáticas) só funciona com números, ela converte uma string vazia `""` para `0`.
21+
3. A adição com uma string adiciona o número `5` à string.
22+
4. A subtração sempre converte para números, então faz `" -9 "` um número `-9` (ignorando espaços em torno dela).
23+
5. `null` torna-se `0` após a conversão numérica.
24+
6. `undefined` torna-se `NaN` após a conversão numérica.

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+
importância: 5
22

33
---
44

5-
# Type conversions
5+
# Tipos de conversões
66

7-
What are results of these expressions?
7+
Quais são os resultados dessas expressões?
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+
Pense bem, escreva e depois compare com a resposta.
Lines changed: 63 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -1,160 +1,160 @@
1-
# Type Conversions
1+
# Tipo Conversões
22

3-
Most of the time, operators and functions automatically convert the values given to them to the right type.
3+
Na maioria das vezes, os operadores e as funções convertem automaticamente os valores dados a eles para o tipo correto.
44

5-
For example, `alert` automatically converts any value to a string to show it. Mathematical operations convert values to numbers.
5+
Por exemplo, o `alert` converte automaticamente qualquer valor para uma string para mostrá-lo. Operações matemáticas convertem valores em números.
66

7-
There are also cases when we need to explicitly convert a value to the expected type.
7+
Há também casos em que precisamos explicitamente converter um valor para o tipo esperado.
88

99
```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>.
10+
Neste capítulo, não cobriremos objectos. Em vez disso, estudaremos os primitivos primeiro. Mais tarde, depois de aprendermos sobre objetos, veremos como a conversão de objetos funciona no capítulo <info:object-toprimitive>.
1111
```
1212

13-
## ToString
13+
## Para String
1414

15-
String conversion happens when we need the string form of a value.
15+
A conversão para strings acontece quando precisamos da forma de string de um valor.
1616

17-
For example, `alert(value)` does it to show the value.
18-
19-
We can also call the `String(value)` function to convert a value to a string:
17+
Por exemplo, `alert(value)` faz isso para mostrar o valor.
2018

19+
Nós também podemos chamar a função `String(value)` para converter um valor em uma string:
2120
```js run
2221
let value = true;
23-
alert(typeof value); // boolean
22+
alert(typeof value); // booleano
2423

2524
*!*
26-
value = String(value); // now value is a string "true"
25+
value = String(value); // agora value é uma string "true"
2726
alert(typeof value); // string
2827
*/!*
2928
```
3029

31-
String conversion is mostly obvious. A `false` becomes `"false"`, `null` becomes `"null"`, etc.
30+
A conversão de strings é mais óbvia. Uma `false` torna-se `"false"`, `null` torna-se `"null"`, etc.
3231

33-
## ToNumber
32+
## Para Número
3433

35-
Numeric conversion happens in mathematical functions and expressions automatically.
34+
A conversão numérica acontece automaticamente em funções e expressões matemáticas.
3635

37-
For example, when division `/` is applied to non-numbers:
36+
Por exemplo, quando a divisão `/` é aplicada para não-numeros:
3837

3938
```js run
40-
alert( "6" / "2" ); // 3, strings are converted to numbers
39+
alert( "6" / "2" ); // 3, strings são convertidas para números
4140
```
4241

43-
We can use the `Number(value)` function to explicitly convert a `value` to a number:
42+
Podemos usar a função `Number(value)` para converter explicitamente um `value` para um 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); // torna-se um número 123
49+
50+
alert(typeof num); // número
5051

51-
alert(typeof num); // number
5252
```
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.
54+
A conversão explícita é normalmente necessária quando lemos um valor de uma fonte baseada em string como um formulário de texto, mas esperamos que um número seja inserido.
5555

56-
If the string is not a valid number, the result of such a conversion is `NaN`. For instance:
56+
Se a cadeia não for um número válido, o resultado de tal conversão é `NaN'. Por exemplo:
5757

5858
```js run
59-
let age = Number("an arbitrary string instead of a number");
59+
let age = Number("uma string arbitrária em vez de um número");
6060

61-
alert(age); // NaN, conversion failed
61+
alert(age); // NaN, conversão falhou
6262
```
6363

64-
Numeric conversion rules:
64+
Regras de conversão numéricas:
6565

66-
| Value | Becomes... |
66+
| Valor | Torna-se... |
6767
|-------|-------------|
6868
|`undefined`|`NaN`|
6969
|`null`|`0`|
7070
|<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`. |
71+
| `string` | Espaços em branco do ínicio e fim são removidos. Se a string restante estiver vazia, o resultado é `0`. Casa contrário, o número é "lido" a partir da string. Um erro dá `NaN`. |
7272

73-
Examples:
73+
Exemplos:
7474

7575
```js run
7676
alert( Number(" 123 ") ); // 123
77-
alert( Number("123z") ); // NaN (error reading a number at "z")
77+
alert( Number("123z") ); // NaN (erro ao ler um número em "z")
7878
alert( Number(true) ); // 1
7979
alert( Number(false) ); // 0
8080
```
8181

82-
Please note that `null` and `undefined` behave differently here: `null` becomes zero while `undefined` becomes `NaN`.
82+
Por favor note que `null` e `undefined` se comportam diferente aqui: `null` torna-se zero enquanto `undefined` torna-se `NaN`.
8383

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.
84+
````smart header="Adição '+' concatenações de strings"
85+
Quase todas as operações matemáticas convertem valores em números. Uma exceção notável é a adição `+`. Se um dos valores adicionados é uma string, a outra também é convertida para uma string.
8686
87-
Then, it concatenates (joins) them:
87+
Então, ele concatena (junta-se a eles):
8888
8989
```js run
90-
alert( 1 + '2' ); // '12' (string to the right)
91-
alert( '1' + 2 ); // '12' (string to the left)
90+
alert( 1 + '2' ); // '12' (string para a direita)
91+
alert( '1' + 2 ); // '12' (string para a esquerda)
9292
```
9393
94-
This only happens when at least one of the arguments is a string. Otherwise, values are converted to numbers.
94+
Isso só acontece quando pelo menos um dos argumentos é uma string. Caso contrário, os valores são convertidos em números.
9595
````
9696

97-
## ToBoolean
97+
## Para Booleano
9898

99-
Boolean conversion is the simplest one.
99+
A conversão booleana é a mais simples.
100100

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)`.
101+
Isso acontece em operações lógicas (mais tarde vamos encontrar testes de condição e outras coisas similares), mas também pode ser feito explicitamente com uma chamada para `Boolean(value)`.
102102

103-
The conversion rule:
103+
A regra de conversão:
104104

105-
- Values that are intuitively "empty", like `0`, an empty string, `null`, `undefined`, and `NaN`, become `false`.
106-
- Other values become `true`.
105+
- Valores que são intuitivamente "vazios", como `0`, uma string vazia, `null`, `undefined`, e `NaN`, tornam-se `false`.
106+
- Outros valores tornam-se `true`.
107107

108-
For instance:
108+
Por exemplo:
109109

110110
```js run
111111
alert( Boolean(1) ); // true
112112
alert( Boolean(0) ); // false
113113

114-
alert( Boolean("hello") ); // true
114+
alert( Boolean("olá") ); // true
115115
alert( Boolean("") ); // false
116116
```
117117

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`.
118+
````warn header="Por favor note: a string com `\"0\"` é `true`"
119+
Algumas linguagens (especificamente PHP) tratam `"0"` como `false`. Mas em JavaScript, uma string não vazia é sempre `true`.
120120

121121
```js run
122122
alert( Boolean("0") ); // true
123-
alert( Boolean(" ") ); // spaces, also true (any non-empty string is true)
123+
alert( Boolean(" ") ); // espaços, também true (qualquer string não vaiza é true)
124124
```
125125
````
126126
127127
128-
## Summary
128+
## Resumo
129129
130-
The three most widely used type conversions are to string, to number, and to boolean.
130+
As três conversões de tipo mais usadas são para string, para número e para booleano.
131131
132-
**`ToString`** -- Occurs when we output something. Can be performed with `String(value)`. The conversion to string is usually obvious for primitive values.
132+
**`Para String`** -- Ocorre quando produzimos algo. Pode ser executado com `String(value)`. A conversão para string é geralmente óbvia para valores primitivos.
133133
134-
**`ToNumber`** -- Occurs in math operations. Can be performed with `Number(value)`.
134+
**`Para Número`** -- Ocorre em operações matemáticas. Pode ser executado com `Number(value)`.
135135
136-
The conversion follows the rules:
136+
Regras de conversão numéricas:
137137
138-
| Value | Becomes... |
138+
| Valor | Torna-se... |
139139
|-------|-------------|
140140
|`undefined`|`NaN`|
141141
|`null`|`0`|
142-
|<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`. |
142+
|<code>true&nbsp;and&nbsp;false</code> | `1` and `0` |
143+
| `string` | Espaços em branco do ínicio e fim são removidos. Se a string restante estiver vazia, o resultado é `0`. Casa contrário, o número é "lido" a partir da string. Um erro dá `NaN`. |
144144
145-
**`ToBoolean`** -- Occurs in logical operations. Can be performed with `Boolean(value)`.
145+
**`Para Booleano`** -- Ocorre em operações lógicas. Pode ser executado com `Boolean(value)`.
146146
147-
Follows the rules:
147+
Segue as regras:
148148
149-
| Value | Becomes... |
149+
| Valor | Torna-se... |
150150
|-------|-------------|
151151
|`0`, `null`, `undefined`, `NaN`, `""` |`false`|
152-
|any other value| `true` |
152+
|qualquer outro valor| `true` |
153153
154154
155-
Most of these rules are easy to understand and memorize. The notable exceptions where people usually make mistakes are:
155+
A maioria destas regras são fáceis de entender e memorizar. As exceções notáveis onde as pessoas normalmente cometem erros são:
156156
157-
- `undefined` is `NaN` as a number, not `0`.
158-
- `"0"` and space-only strings like `" "` are true as a boolean.
157+
- `undefined` is `NaN` como um número, não `0`.
158+
- `"0"` e strings com espaço apenas `" "` são verdadeiras como booleanas.
159159
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.
160+
Objetos não são abordados aqui. Voltaremos a eles mais tarde no capítulo <info:object-toprimitive> que é dedicado exclusivamente a objetos, depois de aprendermos coisas mais básicas sobre JavaScript.

0 commit comments

Comments
 (0)