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/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.
Copy file name to clipboardExpand all lines: 1-js/02-first-steps/15-function-basics/article.md
+34-21Lines changed: 34 additions & 21 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -20,10 +20,10 @@ function showMessage() {
20
20
}
21
21
```
22
22
23
-
A palavra-chave `function` vem primeiro, depois vem o *nome da função*, e uma lista de *parâmetros* entre os parêntesis (vazio no exemplo acima) e finalmente o código da função, também chamado de "o corpo da função", entre chaves.
23
+
A palavra-chave `function` vem primeiro, depois vem o *nome da função*, e uma lista de *parâmetros* entre os parêntesis (separados por vírgulas, vazia no exemplo acima, veremos exemplos mais tarde) e finalmente o código da função, também chamado de "o corpo da função", entre chaves.
When the function is called in lines `(*)` and `(**)`, the given values are copied to local variables `from` and `text`. Then the function uses them.
156
154
157
155
Here'sonemoreexample:wehaveavariable`from`andpassittothefunction. Please note: the function changes `from`, but the change is not seen outside, because a function always gets a copy of the value:
When a value is passed as a function parameter, it's also called an *argument*.
176
+
177
+
In other words, to put these terms straight:
178
+
179
+
- A parameter is the variable listed inside the parentheses in the function declaration (it's a declaration time term)
180
+
- An argument is the value that is passed to the function when it is called (it's a call time term).
181
+
182
+
We declare functions listing their parameters, then call them passing arguments.
183
+
184
+
In the example above, one might say: "the function `sayMessage` is declared with two parameters, then called with two arguments: `from` and `"Hello"`".
185
+
186
+
178
187
## Default values
179
188
180
-
If a parameter is not provided, then its value becomes `undefined`.
189
+
If a function is called, but an argument is not provided, then the corresponding value becomes `undefined`.
181
190
182
191
For instance, the aforementioned function `showMessage(from, text)` can be called with a single argument:
183
192
184
193
```js
185
194
showMessage("Ann");
186
195
```
187
196
188
-
That's not an error. Such a call would output `"Ann: undefined"`. There's no `text`, so it's assumed that `text===undefined`.
197
+
That's not an error. Such a call would output `"*Ann*: undefined"`. As the value for `text` isn't passed, it becomes `undefined`.
189
198
190
-
If we want to use a "default" `text` in this case, then we can specify it after`=`:
199
+
We can specify the so-called "default" (to use if omitted) value for a parameter in the function declaration, using`=`:
191
200
192
201
```jsrun
193
202
functionshowMessage(from, *!*text="no text given"*/!*) {
@@ -211,19 +220,23 @@ function showMessage(from, text = anotherFunction()) {
211
220
```smartheader="Evaluation of default parameters"
212
221
InJavaScript, adefaultparameterisevaluatedeverytimethefunction is called without the respective parameter.
213
222
214
-
In the example above, `anotherFunction()` is called every time `showMessage()` is called without the `text` parameter.
223
+
In the example above, `anotherFunction()` isn't called at all, if the `text` parameter is provided.
224
+
225
+
On the other hand, it's independently called every time when `text` is missing.
215
226
```
216
227
217
228
### Alternative default parameters
218
229
219
-
Sometimes it makes sense to set default values for parameters not in the function declaration, but at a later stage, during its execution.
230
+
Sometimes it makes sense to assign default values for parameters not in the function declaration, but at a later stage.
220
231
221
-
To check for an omitted parameter, we can compare it with `undefined`:
232
+
We can check if the parameter is passed during the function execution, by comparing it with `undefined`:
222
233
223
234
```js run
224
235
function showMessage(text) {
236
+
// ...
237
+
225
238
*!*
226
-
if (text ===undefined) {
239
+
if (text ===undefined) {// if the parameter is missing
227
240
text ='empty message';
228
241
}
229
242
*/!*
@@ -234,21 +247,21 @@ function showMessage(text) {
234
247
showMessage(); // empty message
235
248
```
236
249
237
-
...Or we could use the `||` operator:
250
+
...Or we could use the `??` operator:
238
251
239
252
```js
240
-
// if text parameter is omitted or "" is passed, set it to 'empty'
241
253
functionshowMessage(text) {
254
+
// if text is undefined or otherwise falsy, set it to 'empty'
242
255
text = text ||'empty';
243
256
...
244
257
}
245
258
```
246
259
247
-
Modern JavaScript engines support the [nullish coalescing operator](info:nullish-coalescing-operator) `??`, it's better when falsy values, such as `0`, are considered regular:
260
+
Modern JavaScript engines support the [nullish coalescing operator](info:nullish-coalescing-operator) `??`, it's better when most falsy values, such as `0`, should be considered "normal":
248
261
249
262
```js run
250
-
// if there's no "count" parameter, show "unknown"
251
263
functionshowCount(count) {
264
+
// if count is undefined or null, show "unknown"
252
265
alert(count ??"unknown");
253
266
}
254
267
@@ -411,7 +424,7 @@ Functions that are used *very often* sometimes have ultrashort names.
411
424
412
425
For example, the [jQuery](http://jquery.com) framework defines a function with `$`. The [Lodash](http://lodash.com/) library has its core function named `_`.
413
426
414
-
These are exceptions. Generally functions names should be concise and descriptive.
427
+
These are exceptions. Generally function names should be concise and descriptive.
Copy file name to clipboardExpand all lines: 1-js/04-object-basics/06-constructor-new/article.md
+5-4Lines changed: 5 additions & 4 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -64,13 +64,14 @@ Now if we want to create other users, we can call `new User("Ann")`, `new User("
64
64
65
65
That's the main purpose of constructors -- to implement reusable object creation code.
66
66
67
-
Let's note once again -- technically, any function can be used as a constructor. That is: any function can be run with `new`, and it will execute the algorithm above. The "capital letter first" is a common agreement, to make it clear that a function is to be run with `new`.
67
+
Let's note once again -- technically, any function (except arrow functions, as they don't have `this`) can be used as a constructor. It can be run with `new`, and it will execute the algorithm above. The "capital letter first" is a common agreement, to make it clear that a function is to be run with `new`.
68
68
69
69
````smart header="new function() { ... }"
70
-
If we have many lines of code all about creation of a single complex object, we can wrap them in constructor function, like this:
70
+
If we have many lines of code all about creation of a single complex object, we can wrap them in an immediately called constructor function, like this:
71
71
72
72
```js
73
-
let user = new function() {
73
+
// create a function and immediately call it with new
74
+
let user = new function() {
74
75
this.name = "John";
75
76
this.isAdmin = false;
76
77
@@ -80,7 +81,7 @@ let user = new function() {
80
81
};
81
82
```
82
83
83
-
The constructor can't be called again, because it is not saved anywhere, just created and called. So this trick aims to encapsulate the code that constructs the single object, without future reuse.
84
+
This constructor can't be called again, because it is not saved anywhere, just created and called. So this trick aims to encapsulate the code that constructs the single object, without future reuse.
0 commit comments