Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ null + 1 = 1 // (5)
undefined + 1 = NaN // (6)
```

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.
2. The subtraction `-` (like most math operations) only works with numbers, it converts an empty string `""` to `0`.
3. The addition with a string appends the number `5` to the string.
4. The subtraction always converts to numbers, so it makes `" -9 "` a number `-9` (ignoring spaces around it).
5. `null` becomes `0` after the numeric conversion.
6. `undefined` becomes `NaN` after the numeric conversion.
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.
2. A subtração `-` (como a maioria das operações matemáticas) só funciona com números, ela converte uma string vazia `""` para `0`.
3. A adição com uma string adiciona o número `5` à string.
4. A subtração sempre converte para números, então faz `" -9 "` um número `-9` (ignorando espaços em torno dela).
5. `null` torna-se `0` após a conversão numérica.
6. `undefined` torna-se `NaN` após a conversão numérica.
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
importance: 5
importância: 5

---

# Type conversions
# Tipos de conversões

What are results of these expressions?
Quais são os resultados dessas expressões?

```js no-beautify
"" + 1 + 0
Expand All @@ -23,4 +23,4 @@ null + 1
undefined + 1
```

Think well, write down and then compare with the answer.
Pense bem, escreva e depois compare com a resposta.
126 changes: 63 additions & 63 deletions 1-js/02-first-steps/06-type-conversions/article.md
Original file line number Diff line number Diff line change
@@ -1,160 +1,160 @@
# Type Conversions
# Tipo Conversões

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

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

There are also cases when we need to explicitly convert a value to the expected type.
Há também casos em que precisamos explicitamente converter um valor para o 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>.
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>.
```

## ToString
## Para String

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

For example, `alert(value)` does it to show the value.

We can also call the `String(value)` function to convert a value to a string:
Por exemplo, `alert(value)` faz isso para mostrar o valor.

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

*!*
value = String(value); // now value is a string "true"
value = String(value); // agora value é uma string "true"
alert(typeof value); // string
*/!*
```

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

## ToNumber
## Para Número

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

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

```js run
alert( "6" / "2" ); // 3, strings are converted to numbers
alert( "6" / "2" ); // 3, strings são convertidas para números
```

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

```js run
let str = "123";
alert(typeof str); // string

let num = Number(str); // becomes a number 123
let num = Number(str); // torna-se um número 123

alert(typeof num); // número

alert(typeof num); // number
```

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.
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.

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

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

alert(age); // NaN, conversion failed
alert(age); // NaN, conversão falhou
```

Numeric conversion rules:
Regras de conversão numéricas:

| Value | Becomes... |
| Valor | Torna-se... |
|-------|-------------|
|`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` | 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`. |

Examples:
Exemplos:

```js run
alert( Number(" 123 ") ); // 123
alert( Number("123z") ); // NaN (error reading a number at "z")
alert( Number("123z") ); // NaN (erro ao ler um número em "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`.
Por favor note que `null` e `undefined` se comportam diferente aqui: `null` torna-se zero enquanto `undefined` torna-se `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="Adição '+' concatenações de strings"
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.

Then, it concatenates (joins) them:
Então, ele concatena (junta-se a eles):

```js run
alert( 1 + '2' ); // '12' (string to the right)
alert( '1' + 2 ); // '12' (string to the left)
alert( 1 + '2' ); // '12' (string para a direita)
alert( '1' + 2 ); // '12' (string para a esquerda)
```

This only happens when at least one of the arguments is a string. Otherwise, values are converted to numbers.
Isso só acontece quando pelo menos um dos argumentos é uma string. Caso contrário, os valores são convertidos em números.
````

## ToBoolean
## Para Booleano

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

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)`.
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)`.

The conversion rule:
A regra de conversão:

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

For instance:
Por exemplo:

```js run
alert( Boolean(1) ); // true
alert( Boolean(0) ); // false

alert( Boolean("hello") ); // true
alert( Boolean("olá") ); // 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="Por favor note: a string com `\"0\"` é `true`"
Algumas linguagens (especificamente PHP) tratam `"0"` como `false`. Mas em JavaScript, uma string não vazia é sempre `true`.

```js run
alert( Boolean("0") ); // true
alert( Boolean(" ") ); // spaces, also true (any non-empty string is true)
alert( Boolean(" ") ); // espaços, também true (qualquer string não vaiza é true)
```
````


## Summary
## Resumo

The three most widely used type conversions are to string, to number, and to boolean.
As três conversões de tipo mais usadas são para string, para número e para booleano.

**`ToString`** -- Occurs when we output something. Can be performed with `String(value)`. The conversion to string is usually obvious for primitive values.
**`Para String`** -- Ocorre quando produzimos algo. Pode ser executado com `String(value)`. A conversão para string é geralmente óbvia para valores primitivos.

**`ToNumber`** -- Occurs in math operations. Can be performed with `Number(value)`.
**`Para Número`** -- Ocorre em operações matemáticas. Pode ser executado com `Number(value)`.

The conversion follows the rules:
Regras de conversão numéricas:

| Value | Becomes... |
| Valor | Torna-se... |
|-------|-------------|
|`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`. |
|<code>true&nbsp;and&nbsp;false</code> | `1` and `0` |
| `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`. |

**`ToBoolean`** -- Occurs in logical operations. Can be performed with `Boolean(value)`.
**`Para Booleano`** -- Ocorre em operações lógicas. Pode ser executado com `Boolean(value)`.

Follows the rules:
Segue as regras:

| Value | Becomes... |
| Valor | Torna-se... |
|-------|-------------|
|`0`, `null`, `undefined`, `NaN`, `""` |`false`|
|any other value| `true` |
|qualquer outro valor| `true` |


Most of these rules are easy to understand and memorize. The notable exceptions where people usually make mistakes are:
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:

- `undefined` is `NaN` as a number, not `0`.
- `"0"` and space-only strings like `" "` are true as a boolean.
- `undefined` is `NaN` como um número, não `0`.
- `"0"` e strings com espaço apenas `" "` são verdadeiras como booleanas.

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.
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.
4 changes: 2 additions & 2 deletions 1-js/02-first-steps/index.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
# JavaScript Fundamentals
# Fundamentos JavaScript

Let's learn the fundamentals of script building.
Vamos aprender os fundamentos da construção de scripts.