You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: 1-js/01-getting-started/1-intro/article.md
+1-1Lines changed: 1 addition & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -26,7 +26,7 @@ Interpretadores diferentes têm "codinomes" diferentes. Por exemplo:
26
26
27
27
-[V8](https://en.wikipedia.org/wiki/V8_(JavaScript_engine)) -- no Chrome e no Opera.
28
28
-[SpiderMonkey](https://en.wikipedia.org/wiki/SpiderMonkey) -- no Firefox.
29
-
- ...Há outros codinomes como "Chakra" para o IE, "ChakraCore" para Microsoft Edge, "Nitro" e "SquirrelFish" para Safari, etc.
29
+
- ...Há outros codinomes como "Chakra" para o IE, "JavaScriptCore", "Nitro" e "SquirrelFish" para Safari, etc.
30
30
31
31
Os termos acima são bons para lembrar, pois são usados em artigos de desenvolvedores na internet. Vamos usá-los também. Por exemplo, se "um recurso X é suportado pelo V8", então ele provavelmente funciona no Chrome e no Opera.
Copy file name to clipboardExpand all lines: 1-js/01-getting-started/2-manuals-specifications/article.md
+1-5Lines changed: 1 addition & 5 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -17,16 +17,12 @@ E mais, se você está desenvolvendo para browsers, há outras especificações
17
17
18
18
## Manuais
19
19
20
-
-**MDN (Mozilla) JavaScript Reference** é um manual com exemplos e outras informações. É ótimo para um entendimento sobre funções, métodos da linguagem, etc.
20
+
-**MDN (Mozilla) JavaScript Reference** é um manual com exemplos e outras informações. É ótimo para um entendimento sobre funçõesda linguagem, métodos , etc.
21
21
22
22
Pode ser encontrado em <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference>.
23
23
24
24
Porém, às vezes é melhor fazer uma busca na internet. Apenas use "MDN [termo]" na busca, por exemplo: <https://google.com/search?q=MDN+parseInt> para procurar pela função `parseInt`.
25
25
26
-
-**MSDN** - Manual da Microsoft com muitas informações, incluindo JavaScript (frequentemente referido como JScript). Se precisar de algo específico para o Internet Explorer, é melhor ir por aqui: <http://msdn.microsoft.com/>.
27
-
28
-
Assim como para o manual da Mozilla, também podemos fazer uma busca na internet com frases do tipo "RegExp MSDN" ou "RegExp MSDN jscript".
29
-
30
26
## Tabelas de compatibilidade
31
27
32
28
JavaScript é uma linguagem em desenvolvimento, novas funcionalidades são adicionadas regularmente.
Copy file name to clipboardExpand all lines: 1-js/02-first-steps/02-structure/article.md
+16-20Lines changed: 16 additions & 20 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -46,7 +46,7 @@ alert(3 +
46
46
+2);
47
47
```
48
48
49
-
O código produz `6` porque o Javascript não insere pontos e virgulas aqui. É intuitivamente óbvio que se a linha termina com um sinal de mais `"+"`, então é uma "expressão incompleta", logo o ponto e vírgula não é necessário. E neste caso isso funciona como pretendido.
49
+
O código produz `6` porque o Javascript não insere pontos e virgulas aqui. É intuitivamente óbvio que se a linha termina com um sinal de mais `"+"`, então é uma "expressão incompleta", logo o ponto e vírgula aí seria incorreto. E neste caso isso funciona como pretendido.
50
50
51
51
**Mas há situações em que o JavaScript "falha" em assumir um ponto e vírgula onde ele é realmente necessário.**
52
52
@@ -56,40 +56,36 @@ Erros que ocorrem em tais casos são bastante difíceis de encontrar e corrigir.
56
56
Se você está curioso para ver um exemplo concreto de tal erro, verifique este código:
57
57
58
58
```js run
59
-
[1, 2].forEach(alert)
59
+
alert("Hello");
60
+
61
+
[1, 2].forEach(alert);
60
62
```
61
63
62
-
Não há necessidade de pensar sobre o significado dos parênteses `[]` e `forEach` ainda. Nós vamos estudá-los mais tarde. Por enquanto, apenas lembre-se que o resultado do código: mostra `1` e depois` 2`.
64
+
Não há necessidade de pensar sobre o significado dos parênteses `[]` e também do `forEach`. Nós vamos estudá-los mais tarde. Por enquanto, apenas lembre-se do resultado da execução do código: ele mostra `Hello`, depois `1`, e depois` 2`.
63
65
64
-
Agora, vamos adicionar um `alert` antes do código e * não * terminá-lo com um ponto e vírgula:
66
+
Agora, vamos remover o ponto e vírgula depois do `alert`:
65
67
66
68
```js run no-beautify
67
-
alert("Haverá um erro")
69
+
alert("Hello")
68
70
69
-
[1, 2].forEach(alert)
71
+
[1, 2].forEach(alert);
70
72
```
71
73
72
-
Agora, se nós executarmos o código, apenas o primeiro `alert` é mostrado e então temos um erro!
73
-
74
-
Mas tudo está bem novamente se adicionarmos um ponto e vírgula após `alert`:
75
-
```js run
76
-
alert("Tudo bem agora");
74
+
A diferença em comparação com o código acima é de apenas um caractere: o ponto e vírgula da primeira linha se foi.
77
75
78
-
[1, 2].forEach(alert)
79
-
```
76
+
Se nós executarmos esse código, apenas o primeiro `Hello` é mostrado (e então há um erro, você pode precisar de abrir a consola para o ver). Já não existem mais números.
80
77
81
-
Agora temos a mensagem "Tudo bem agora" seguida por "1" e "2".
78
+
Isso ocorre porque o JavaScript não assume um ponto e vírgula antes dos colchetes `[...]`. Portanto, o código no último exemplo é tratado como uma única instrução.
82
79
83
-
84
-
O erro na variante sem ponto e vírgula ocorre porque o JavaScript não assume um ponto e vírgula antes dos colchetes `[...]`.
85
-
86
-
Portanto, como o ponto e vírgula não é inserido automaticamente, o código no primeiro exemplo é tratado como uma única instrução. Veja como o mecanismo vê isso:
80
+
Veja como o mecanismo vê isso:
87
81
88
82
```js run no-beautify
89
-
alert("Haverá um erro")[1, 2].forEach(alert)
83
+
alert("Hello")[1, 2].forEach(alert);
90
84
```
91
85
92
-
Mas devem ser duas declarações separadas, não uma. Tal fusão neste caso é completamente errado, daí o erro. Isso pode acontecer em outras situações.
86
+
Parece estranho, não? Tal fusão neste caso é completamente errada. Nós precisamos de colocar um ponto e vírgula depois de `alert` para o código funcionar corretamente.
87
+
88
+
Isso também pode acontecer em outras situações.
93
89
````
94
90
95
91
Recomendamos colocar ponto e vírgula entre as frases, mesmo que estejam separadas por novas linhas. Esta regra é amplamente adotada pela comunidade. Vamos notar mais uma vez -- *é possível* deixar de fora os pontos e vírgulas na maior parte do tempo. Mas é mais seguro -- especialmente para um iniciante -- usá-los.
Copy file name to clipboardExpand all lines: 1-js/02-first-steps/05-types/article.md
+1-1Lines changed: 1 addition & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -64,7 +64,7 @@ Os valores numéricos especiais pertencem formalmente ao tipo "número". Claro q
64
64
65
65
Veremos mais sobre como trabalhar com números no capítulo <info:number>.
66
66
67
-
## BigInt
67
+
## BigInt [#bigint-type]
68
68
69
69
In JavaScript, the "number" type cannot represent integer values larger than <code>(2<sup>53</sup>-1)</code> (that's `9007199254740991`), or less than <code>-(2<sup>53</sup>-1)</code> for negatives. It's a technical limitation caused by their internal representation.
Mathematically, the exponentiation is defined for non-integer numbers as well. For example, a square root is an exponentiation by `1/2`:
71
+
Just like in maths, the exponentiation operator is defined for non-integer numbers as well.
72
+
73
+
For example, a square root is an exponentiation by ½:
70
74
71
75
```js run
72
76
alert( 4 ** (1/2) ); // 2 (power of 1/2 is the same as a square root)
@@ -104,7 +108,7 @@ Here's a more complex example:
104
108
alert(2 + 2 + '1' ); // "41" and not "221"
105
109
```
106
110
107
-
Here, operators work one after another. The first `+` sums two numbers, so it returns `4`, then the next `+` adds the string `1` to it, so it's like `4 + '1' = 41`.
111
+
Here, operators work one after another. The first `+` sums two numbers, so it returns `4`, then the next `+` adds the string `1` to it, so it's like `4 + '1' = '41'`.
Copy file name to clipboardExpand all lines: 1-js/02-first-steps/11-logical-operators/article.md
+2-2Lines changed: 2 additions & 2 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,6 +1,6 @@
1
1
# Logical operators
2
2
3
-
There are three logical operators in JavaScript: `||` (OR), `&&` (AND), `!` (NOT).
3
+
There are four logical operators in JavaScript: `||` (OR), `&&` (AND), `!` (NOT), `??` (Nullish Coalescing). Here we cover the first three, the `??` operator is in the next article.
4
4
5
5
Although they are called "logical", they can be applied to values of any type, not only boolean. Their result can also be of any type.
Copy file name to clipboardExpand all lines: 1-js/02-first-steps/12-nullish-coalescing-operator/article.md
+18-15Lines changed: 18 additions & 15 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -2,15 +2,14 @@
2
2
3
3
[recent browser="new"]
4
4
5
-
Here, in this article, we'll say that an expression is "defined" when it's neither `null` nor `undefined`.
6
-
7
5
The nullish coalescing operator is written as two question marks `??`.
8
6
7
+
As it treats `null` and `undefined` similarly, we'll use a special term here, in this article. We'll say that an expression is "defined" when it's neither `null` nor `undefined`.
8
+
9
9
The result of `a ?? b` is:
10
10
- if `a` is defined, then `a`,
11
11
- if `a` isn't defined, then `b`.
12
12
13
-
14
13
In other words, `??` returns the first argument if it's not `null/undefined`. Otherwise, the second one.
15
14
16
15
The nullish coalescing operator isn't anything completely new. It's just a nice syntax to get the first "defined" value of the two.
@@ -21,29 +20,31 @@ We can rewrite `result = a ?? b` using the operators that we already know, like
21
20
result = (a !==null&& a !==undefined) ? a : b;
22
21
```
23
22
23
+
Now it should be absolutely clear what `??` does. Let's see where it helps.
24
+
24
25
The common use case for `??` is to provide a default value for a potentially undefined variable.
25
26
26
-
For example, here we show `Anonymous` if `user` isn't defined:
27
+
For example, here we show `user` if defined, otherwise `Anonymous`:
27
28
28
29
```js run
29
30
let user;
30
31
31
-
alert(user ??"Anonymous"); // Anonymous
32
+
alert(user ??"Anonymous"); // Anonymous (user not defined)
32
33
```
33
34
34
-
Of course, if `user`had any value except `null/undefined`, then we would see it instead:
35
+
Here's the example with `user`assigned to a name:
35
36
36
37
```js run
37
38
let user ="John";
38
39
39
-
alert(user ??"Anonymous"); // John
40
+
alert(user ??"Anonymous"); // John (user defined)
40
41
```
41
42
42
43
We can also use a sequence of `??` to select the first value from a list that isn't `null/undefined`.
43
44
44
-
Let's say we have a user's data in variables `firstName`, `lastName` or `nickName`. All of them may be undefined, if the user decided not to enter a value.
45
+
Let's say we have a user's data in variables `firstName`, `lastName` or `nickName`. All of them may be not defined, if the user decided not to enter a value.
45
46
46
-
We'd like to display the user name using one of these variables, or show "Anonymous" if all of them are undefined.
47
+
We'd like to display the user name using one of these variables, or show "Anonymous" if all of them aren't defined.
The OR `||` operator exists since the beginning of JavaScript, so developers were using it for such purposes for a long time.
79
+
Historically, the OR `||` operator was there first. It exists since the beginning of JavaScript, so developers were using it for such purposes for a long time.
79
80
80
81
On the other hand, the nullish coalescing operator `??` was added to JavaScript only recently, and the reason for that was that people weren't quite happy with `||`.
81
82
@@ -96,16 +97,18 @@ alert(height || 100); // 100
96
97
alert(height ??100); // 0
97
98
```
98
99
99
-
- The `height ||100` checks `height` for being a falsy value, and it really is.
100
-
- so the result is the second argument, `100`.
100
+
- The `height ||100` checks `height` for being a falsy value, and it's `0`, falsy indeed.
101
+
- so the result of `||`is the second argument, `100`.
101
102
- The `height ??100` checks `height` for being `null/undefined`, and it's not,
102
103
- so the result is `height` "as is", that is `0`.
103
104
104
-
If the zero height is a valid value, that shouldn't be replaced with the default, then`??` does just the right thing.
105
+
In practice, the zero height is often a valid value, that shouldn't be replaced with the default. So`??` does just the right thing.
105
106
106
107
## Precedence
107
108
108
-
The precedence of the `??` operator is rather low: `5` in the [MDN table](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#Table). So `??` is evaluated before `=` and `?`, but after most other operations, such as `+`, `*`.
109
+
The precedence of the `??` operator is about the same as `||`, just a bit lower. It equals `5` in the [MDN table](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#Table), while `||` is `6`.
110
+
111
+
That means that, just like `||`, the nullish coalescing operator `??` is evaluated before `=` and `?`, but after most other operations, such as `+`, `*`.
109
112
110
113
So if we'd like to choose a value with `??` in an expression with other operators, consider adding parentheses:
111
114
@@ -139,7 +142,7 @@ The code below triggers a syntax error:
139
142
let x =1&&2??3; // Syntax error
140
143
```
141
144
142
-
The limitation is surely debatable, but it was added to the language specification with the purpose to avoid programming mistakes, when people start to switch to `??` from `||`.
145
+
The limitation is surely debatable, it was added to the language specification with the purpose to avoid programming mistakes, when people start to switch from `||` to `??`.
0 commit comments