Skip to content

Commit 959db73

Browse files
authored
Merge pull request #212 from PauloBacelar/master
Type Conversions
2 parents 37da7e2 + 5177ed7 commit 959db73

File tree

1 file changed

+59
-59
lines changed

1 file changed

+59
-59
lines changed
Lines changed: 59 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -1,150 +1,150 @@
1-
# Type Conversions
1+
# Conversões de Tipo
22

3-
Most of the time, operators and functions automatically convert the values given to them to the right type.
3+
Na maior parte do tempo, operadores e funções convertem os valores dados a eles para o tipo certo automaticamente.
44

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

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

9-
```smart header="Not talking about objects yet"
10-
In this chapter, we won't cover objects. For now we'll just be talking about primitives.
9+
```smart header="Não vamos falar de objetos"
10+
Nesse capítulo, não vamos falar sobre objetos. Por agora, vamos abordar apenas os tipos primitivos.
1111
12-
Later, after we learn about objects, in the chapter <info:object-toprimitive> we'll see how objects fit in.
12+
Mais tarde, após abordarmos objetos no capítulo <info:object-toprimitive>, veremos como objetos se comportam em conversões de tipo.
1313
```
1414

15-
## String Conversion
15+
## Conversões para String
1616

17-
String conversion happens when we need the string form of a value.
17+
As conversões para string acontecem quando precisamos da forma string de um valor.
1818

19-
For example, `alert(value)` does it to show the value.
19+
Por exemplo, `alert(value)` faz isso para mostrar o valor.
2020

21-
We can also call the `String(value)` function to convert a value to a string:
21+
Também podemos usar a função `String(value)` para converter um valor para string:
2222

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

2727
*!*
28-
value = String(value); // now value is a string "true"
28+
value = String(value); // agora value é uma string "true"
2929
alert(typeof value); // string
3030
*/!*
3131
```
3232

33-
String conversion is mostly obvious. A `false` becomes `"false"`, `null` becomes `"null"`, etc.
33+
Conversões para string são as mais fáceis. `false` se torna `"false"`, `null` vira `"null"`, e assim por diante.
34+
35+
## Conversões Numéricas
3436

35-
## Numeric Conversion
37+
As conversões numéricas acontecem automaticamente em funções e expressões matemáticas.
3638

37-
Numeric conversion happens in mathematical functions and expressions automatically.
38-
39-
For example, when division `/` is applied to non-numbers:
39+
Por exemplo, quando `/` é usado com valores que não são números:
4040

4141
```js run
42-
alert( "6" / "2" ); // 3, strings are converted to numbers
42+
alert( "6" / "2" ); // 3, strings viram números
4343
```
4444

45-
We can use the `Number(value)` function to explicitly convert a `value` to a number:
45+
Podemos usar a função `Number(value)` para converter `value` para um número.
4646

4747
```js run
4848
let str = "123";
4949
alert(typeof str); // string
5050

51-
let num = Number(str); // becomes a number 123
51+
let num = Number(str); // vira o número 123
5252

5353
alert(typeof num); // number
5454
```
5555

56-
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.
56+
Conversões explícitas geralmente são obrigatórias quando estamos a ler um valor de uma fonte baseada em string - como um texto - mas esperamos receber um valor numérico.
5757

58-
If the string is not a valid number, the result of such a conversion is `NaN`. For instance:
58+
Se a string não é um valor numérico válido, o resultado da conversão é `NaN`. Por exemplo:
5959

6060
```js run
61-
let age = Number("an arbitrary string instead of a number");
61+
let age = Number("uma string ao invés de um número");
6262

63-
alert(age); // NaN, conversion failed
63+
alert(age); // NaN, a conversão falhou
6464
```
6565

66-
Numeric conversion rules:
66+
Regras de conversões numéricas:
6767

68-
| Value | Becomes... |
68+
| Valor | Se torna... |
6969
|-------|-------------|
7070
|`undefined`|`NaN`|
7171
|`null`|`0`|
72-
|<code>true&nbsp;and&nbsp;false</code> | `1` and `0` |
73-
| `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`. |
72+
|<code>true&nbsp;e&nbsp;false</code>| `1` e `0` |
73+
| `string` | Espaços em branco do início e do fim são removidos. Se a string que sobrar for vazia, o resultado é `0`. Senão, o número é "lido" a partir da string. Um erro nos dá `NaN`|
7474

75-
Examples:
75+
Exemplos:
7676

7777
```js run
7878
alert( Number(" 123 ") ); // 123
79-
alert( Number("123z") ); // NaN (error reading a number at "z")
79+
alert( Number("123z") ); // NaN (Erro ao ler um número em "z")
8080
alert( Number(true) ); // 1
8181
alert( Number(false) ); // 0
8282
```
8383

84-
Please note that `null` and `undefined` behave differently here: `null` becomes zero while `undefined` becomes `NaN`.
84+
Note que `null` e `undefined` se comportam de maneira diferente: `null` se torna zero, enquanto `undefined` vira `NaN`.
8585

86-
Most mathematical operators also perform such conversion, we'll see that in the next chapter.
86+
A maioria dos operadores matemáticos também executam essa conversão, o que veremos no próximo capítulo.
8787

88-
## Boolean Conversion
88+
## Conversões Booleanas
8989

90-
Boolean conversion is the simplest one.
90+
Conversões booleanas são as mais simples de todas.
9191

92-
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)`.
92+
Acontecem em operações lógicas (depois veremos testes de condição e outras coisas similares), mas também podem acontecer explicitamente ao usar a função `Boolean(value)`.
9393

94-
The conversion rule:
94+
A regra de conversão:
9595

96-
- Values that are intuitively "empty", like `0`, an empty string, `null`, `undefined`, and `NaN`, become `false`.
97-
- Other values become `true`.
96+
- Valores que são intuitivamente "vazios", como "0", uma string vazia (""), `null`, `undefined` e `NaN`, viram `false`.
97+
- Outros valores viram `true`.
9898

99-
For instance:
99+
Por exemplo:
100100

101101
```js run
102102
alert( Boolean(1) ); // true
103103
alert( Boolean(0) ); // false
104104

105-
alert( Boolean("hello") ); // true
105+
alert( Boolean("Olá") ); // true
106106
alert( Boolean("") ); // false
107107
```
108108

109-
````warn header="Please note: the string with zero `\"0\"` is `true`"
110-
Some languages (namely PHP) treat `"0"` as `false`. But in JavaScript, a non-empty string is always `true`.
109+
````warn header="Note que uma string com um zero `\"0\"` é `true`"
110+
Algumas linguagens de programação (como PHP), tratam `\"0\"` como `false`. Mas no JavaScript, uma string não-vazia sempre é `true`.
111111

112112
```js run
113113
alert( Boolean("0") ); // true
114-
alert( Boolean(" ") ); // spaces, also true (any non-empty string is true)
114+
alert( Boolean(" ") ); // espaços também são true (toda string não-vazia se torna true)
115115
```
116116
````
117117
118-
## Summary
118+
## Sumário
119119
120-
The three most widely used type conversions are to string, to number, and to boolean.
120+
As três conversões mais comuns são para string, number e boolean.
121121
122-
**`String Conversion`** -- Occurs when we output something. Can be performed with `String(value)`. The conversion to string is usually obvious for primitive values.
122+
**`Conversões para String`** -- Ocorrem quando mostramos algum valor. Podem ser explicitamente feitas com `String(value)`. As conversões para string geralmente são óbvias com tipos primitivos.
123123
124-
**`Numeric Conversion`** -- Occurs in math operations. Can be performed with `Number(value)`.
124+
**`Conversões Numéricas`** -- Ocorrem em operações matemáticas. Podem ser feitas com `Number(value)`.
125125
126-
The conversion follows the rules:
126+
A conversão segue as seguintes regras:
127127
128-
| Value | Becomes... |
128+
| Valor | Se torna... |
129129
|-------|-------------|
130130
|`undefined`|`NaN`|
131131
|`null`|`0`|
132-
|<code>true&nbsp;/&nbsp;false</code> | `1 / 0` |
133-
| `string` | The string is read "as is", whitespaces from both sides are ignored. An empty string becomes `0`. An error gives `NaN`. |
132+
|<code>true&nbsp;/&nbsp;false</code>| `1 / 0` |
133+
| `string` | A string é lida "como ela é", espaços em branco do início e do fim são ignorados. Uma string vazia, vira `0`. Um erro nos dá `NaN`|
134134
135-
**`Boolean Conversion`** -- Occurs in logical operations. Can be performed with `Boolean(value)`.
135+
**`Conversões Booleanas`** -- Ocorrem em operações lógicas. Podem ser feitas com `Boolean(value)`.
136136
137-
Follows the rules:
137+
Seguem as regras:
138138
139-
| Value | Becomes... |
139+
| Valor | Se torna... |
140140
|-------|-------------|
141141
|`0`, `null`, `undefined`, `NaN`, `""` |`false`|
142-
|any other value| `true` |
142+
|qualquer outro valor| `true` |
143143
144144
145-
Most of these rules are easy to understand and memorize. The notable exceptions where people usually make mistakes are:
145+
A maior parte dessas regras são fáceis de entender e memorizar. Exceções notáveis em que as pessoas geralmente erram são:
146146
147-
- `undefined` is `NaN` as a number, not `0`.
148-
- `"0"` and space-only strings like `" "` are true as a boolean.
147+
- `undefined` é `NaN` como número, não `0`.
148+
- `"0"` e strings só com espaços `" "` são `true` como booleanos.
149149
150-
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.
150+
Objetos não são citados aqui. Retornaremos depois no capítulo <info:object-toprimitive> que é dedicado exclusivamente a objetos, após aprendermos coisas mais básicas de JavaScript.

0 commit comments

Comments
 (0)