Skip to content

Commit b37a56e

Browse files
authored
Merge pull request #217 from javascript-tutorial/sync-fb4fc33a
Sync with upstream @ fb4fc33
2 parents 453a42f + 60ddea1 commit b37a56e

File tree

46 files changed

+232
-175
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

46 files changed

+232
-175
lines changed

Diff for: 1-js/01-getting-started/1-intro/article.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ Interpretadores diferentes têm "codinomes" diferentes. Por exemplo:
2626

2727
- [V8](https://en.wikipedia.org/wiki/V8_(JavaScript_engine)) -- no Chrome e no Opera.
2828
- [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.
3030

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

Diff for: 1-js/02-first-steps/02-structure/article.md

+16-20
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ alert(3 +
4646
+ 2);
4747
```
4848

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

5151
**Mas há situações em que o JavaScript "falha" em assumir um ponto e vírgula onde ele é realmente necessário.**
5252

@@ -56,40 +56,36 @@ Erros que ocorrem em tais casos são bastante difíceis de encontrar e corrigir.
5656
Se você está curioso para ver um exemplo concreto de tal erro, verifique este código:
5757
5858
```js run
59-
[1, 2].forEach(alert)
59+
alert("Hello");
60+
61+
[1, 2].forEach(alert);
6062
```
6163
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`.
6365
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`:
6567
6668
```js run no-beautify
67-
alert("Haverá um erro")
69+
alert("Hello")
6870
69-
[1, 2].forEach(alert)
71+
[1, 2].forEach(alert);
7072
```
7173
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.
7775
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.
8077
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.
8279
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:
8781
8882
```js run no-beautify
89-
alert("Haverá um erro")[1, 2].forEach(alert)
83+
alert("Hello")[1, 2].forEach(alert);
9084
```
9185
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.
9389
````
9490

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

Diff for: 1-js/02-first-steps/05-types/article.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ Os valores numéricos especiais pertencem formalmente ao tipo "número". Claro q
6464

6565
Veremos mais sobre como trabalhar com números no capítulo <info:number>.
6666

67-
## BigInt
67+
## BigInt [#bigint-type]
6868

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

Diff for: 1-js/02-first-steps/08-operators/article.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -63,8 +63,8 @@ In school maths, we write that as a<sup>b</sup>.
6363
For instance:
6464

6565
```js run
66-
alert( 2 ** 2 ); // 2² = 4
67-
alert( 2 ** 3 ); // 2³ = 8
66+
alert( 2 ** 2 ); // 2² = 4
67+
alert( 2 ** 3 ); // 2³ = 8
6868
alert( 2 ** 4 ); // 2⁴ = 16
6969
```
7070

Diff for: 1-js/02-first-steps/15-function-basics/article.md

+34-21
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,10 @@ function showMessage() {
2020
}
2121
```
2222

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

2525
```js
26-
function name(parameters) {
26+
function name(parameter1, parameter2, ... parameterN) {
2727
...corpo...
2828
}
2929
```
@@ -137,26 +137,23 @@ It's a good practice to minimize the use of global variables. Modern code has fe
137137

138138
## Parameters
139139

140-
We can pass arbitrary data to functions using parameters (also called *function arguments*) .
140+
We can pass arbitrary data to functions using parameters.
141141

142142
In the example below, the function has two parameters: `from` and `text`.
143143

144144
```js run
145-
function showMessage(*!*from, text*/!*) { // arguments: from, text
145+
function showMessage(*!*from, text*/!*) { // parameters: from, text
146146
alert(from + ': ' + text);
147147
}
148148

149-
*!*
150-
showMessage('Ann', 'Hello!'); // Ann: Hello! (*)
151-
showMessage('Ann', "What's up?"); // Ann: What's up? (**)
152-
*/!*
149+
*!*showMessage('Ann', 'Hello!');*/!* // Ann: Hello! (*)
150+
*!*showMessage('Ann', "What's up?");*/!* // Ann: What's up? (**)
153151
```
154152
155153
When the function is called in lines `(*)` and `(**)`, the given values are copied to local variables `from` and `text`. Then the function uses them.
156154
157155
Here's one more example: we have a variable `from` and pass it to the function. Please note: the function changes `from`, but the change is not seen outside, because a function always gets a copy of the value:
158156

159-
160157
```js run
161158
function showMessage(from, text) {
162159

@@ -175,19 +172,31 @@ showMessage(from, "Hello"); // *Ann*: Hello
175172
alert( from ); // Ann
176173
```
177174
175+
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+
178187
## Default values
179188
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`.
181190
182191
For instance, the aforementioned function `showMessage(from, text)` can be called with a single argument:
183192
184193
```js
185194
showMessage("Ann");
186195
```
187196
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`.
189198
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 `=`:
191200
192201
```js run
193202
function showMessage(from, *!*text = "no text given"*/!*) {
@@ -211,19 +220,23 @@ function showMessage(from, text = anotherFunction()) {
211220
```smart header="Evaluation of default parameters"
212221
In JavaScript, a default parameter is evaluated every time the function is called without the respective parameter.
213222

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.
215226
```
216227

217228
### Alternative default parameters
218229

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

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`:
222233

223234
```js run
224235
function showMessage(text) {
236+
// ...
237+
225238
*!*
226-
if (text === undefined) {
239+
if (text === undefined) { // if the parameter is missing
227240
text = 'empty message';
228241
}
229242
*/!*
@@ -234,21 +247,21 @@ function showMessage(text) {
234247
showMessage(); // empty message
235248
```
236249
237-
...Or we could use the `||` operator:
250+
...Or we could use the `??` operator:
238251
239252
```js
240-
// if text parameter is omitted or "" is passed, set it to 'empty'
241253
function showMessage(text) {
254+
// if text is undefined or otherwise falsy, set it to 'empty'
242255
text = text || 'empty';
243256
...
244257
}
245258
```
246259
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":
248261
249262
```js run
250-
// if there's no "count" parameter, show "unknown"
251263
function showCount(count) {
264+
// if count is undefined or null, show "unknown"
252265
alert(count ?? "unknown");
253266
}
254267

@@ -411,7 +424,7 @@ Functions that are used *very often* sometimes have ultrashort names.
411424

412425
For example, the [jQuery](http://jquery.com) framework defines a function with `$`. The [Lodash](http://lodash.com/) library has its core function named `_`.
413426

414-
These are exceptions. Generally functions names should be concise and descriptive.
427+
These are exceptions. Generally function names should be concise and descriptive.
415428
```
416429

417430
## Functions == Comments

Diff for: 1-js/03-code-quality/01-debugging-chrome/article.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Depuração de erros no Chrome
1+
# Depuração de erros no navegador
22

33
Antes de escrevermos código mais complexo, vamos falar de debugging (depuração de erros).
44

Diff for: 1-js/03-code-quality/06-polyfills/article.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ Modern project build systems, such as [webpack](http://webpack.github.io/), prov
4848
4949
New language features may include not only syntax constructs and operators, but also built-in functions.
5050
51-
For example, `Math.trunc(n)` is a function that "cuts off" the decimal part of a number, e.g `Math.trunc(1.23) = 1`.
51+
For example, `Math.trunc(n)` is a function that "cuts off" the decimal part of a number, e.g `Math.trunc(1.23)` returns `1`.
5252
5353
In some (very outdated) JavaScript engines, there's no `Math.trunc`, so such code will fail.
5454

Diff for: 1-js/04-object-basics/04-object-methods/article.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ user = {
8181
// method shorthand looks better, right?
8282
user = {
8383
*!*
84-
sayHi() { // same as "sayHi: function()"
84+
sayHi() { // same as "sayHi: function(){...}"
8585
*/!*
8686
alert("Hello");
8787
}

Diff for: 1-js/04-object-basics/06-constructor-new/article.md

+5-4
Original file line numberDiff line numberDiff line change
@@ -64,13 +64,14 @@ Now if we want to create other users, we can call `new User("Ann")`, `new User("
6464

6565
That's the main purpose of constructors -- to implement reusable object creation code.
6666

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

6969
````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:
7171
7272
```js
73-
let user = new function() {
73+
// create a function and immediately call it with new
74+
let user = new function() {
7475
this.name = "John";
7576
this.isAdmin = false;
7677
@@ -80,7 +81,7 @@ let user = new function() {
8081
};
8182
```
8283
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.
8485
````
8586

8687
## Constructor mode test: new.target

0 commit comments

Comments
 (0)