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
+9Lines changed: 9 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -106,12 +106,21 @@ Ferramentas modernas tornam a transpilação muito rápida e transparente, permi
106
106
107
107
Exemplos de tais linguagens:
108
108
109
+
<<<<<<< HEAD
109
110
-[CoffeeScript](http://coffeescript.org/) é um "açúcar sintático" para JavaScript. Ele introduz uma sintaxe mais curta, permitindo-nos escrever um código mais claro e preciso. Normalmente, Ruby devs gostam dele.
110
111
-[TypeScript](http://www.typescriptlang.org/) está concentrado em adicionar "estritos tipos de dados" para simplificar o desenvolvimento e suporte de sistemas complexos. É desenvolvido pela Microsoft.
111
112
-[Flow](http://flow.org/) também adiciona tipos de dados, mas de uma forma diferente. Desenvolvido pela Facebook.
112
113
-[Dart](https://www.dartlang.org/) é uma linguagem autônoma que tem seu próprio interpretador que roda em ambientes fora do navegador (como aplicativos móveis), mas também pode ser transpilada para JavaScript. Desenvolvida pela Google.
113
114
-[Brython](https://brython.info/) é um transpilador de Python para JavaScript que permite escrever aplicativos em puro Python, sem JavaScript.
114
115
-[Kotlin](https://kotlinlang.org/docs/js-overview.html) é uma linguagem de programação moderna, concisa e segura, que pode ser usada no navegador ou no Node.
116
+
=======
117
+
-[CoffeeScript](http://coffeescript.org/) is a "syntactic sugar" for JavaScript. It introduces shorter syntax, allowing us to write clearer and more precise code. Usually, Ruby devs like it.
118
+
-[TypeScript](http://www.typescriptlang.org/) is concentrated on adding "strict data typing" to simplify the development and support of complex systems. It is developed by Microsoft.
119
+
-[Flow](http://flow.org/) also adds data typing, but in a different way. Developed by Facebook.
120
+
-[Dart](https://www.dartlang.org/) is a standalone language that has its own engine that runs in non-browser environments (like mobile apps), but also can be transpiled to JavaScript. Developed by Google.
121
+
-[Brython](https://brython.info/) is a Python transpiler to JavaScript that enables the writing of applications in pure Python without JavaScript.
122
+
-[Kotlin](https://kotlinlang.org/docs/reference/js-overview.html) is a modern, concise and safe programming language that can target the browser or Node.
123
+
>>>>>>> 468e3552884851fcef331fbdfd58096652964b5f
115
124
116
125
Há mais. Claro que, mesmo que usemos uma dessas linguagens transpiladas, também devemos saber JavaScript para entender o que estamos fazendo.
Copy file name to clipboardExpand all lines: 1-js/03-code-quality/01-debugging-chrome/article.md
+5Lines changed: 5 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -134,8 +134,13 @@ Existem botões para isso no topo do painel direito. Vamos interagir com eles.
134
134
135
135
Continuando a clicar nele, passará por todas as instruções do programa, uma por uma.
136
136
137
+
<<<<<<< HEAD
137
138
<spanclass="devtools"style="background-position:-62px-192px"></span> -- "Step over": execute o próximo comando, mas *mas não vá para dentro de uma função*, atalho `key:F10`.
138
139
: Similar ao comando "Step" anterior, mas com um comportamento diferente se a próxima instrução for uma chamada de função. Isto é: não uma incorporada (*built-in*), como `alert`, mas uma função sua.
140
+
=======
141
+
<spanclass="devtools"style="background-position:-62px-192px"></span> -- "Step over": run the next command, but *don't go into a function*, hotkey `key:F10`.
142
+
: Similar to the previous "Step" command, but behaves differently if the next statement is a function call. That is: not a built-in, like `alert`, but a function of our own.
143
+
>>>>>>> 468e3552884851fcef331fbdfd58096652964b5f
139
144
140
145
O comando "Step", vai para dentro dela e suspende a execução na sua primeira linha, ao contrário de "Step over" que executa essa chamada de função aninhada invisívelmente, saltando sobre o funcionamento interno da função.
Copy file name to clipboardExpand all lines: 1-js/05-data-types/10-destructuring-assignment/article.md
+65-26Lines changed: 65 additions & 26 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -2,35 +2,50 @@
2
2
3
3
The two most used data structures in JavaScript are `Object` and `Array`.
4
4
5
+
<<<<<<< HEAD
5
6
Objects allow us to pack many pieces of information into a single entity and arrays allow us to store ordered collections. So we can make an object or an array and handle it as a single entity, or maybe pass it to a function call.
6
7
7
8
*Destructuring assignment* is a special syntax that allows us to "unpack" arrays or objects into a bunch of variables, as sometimes they are more convenient. Destructuring also works great with complex functions that have a lot of parameters, default values, and soon we'll see how these are handled too.
9
+
=======
10
+
- Objects allow us to create a single entity that stores data items by key.
11
+
- Arrays allow us to gather data items into an ordered list.
12
+
13
+
Although, when we pass those to a function, it may need not an object/array as a whole. It may need individual pieces.
14
+
15
+
*Destructuring assignment* is a special syntax that allows us to "unpack" arrays or objects into a bunch of variables, as sometimes that's more convenient.
16
+
17
+
Destructuring also works great with complex functions that have a lot of parameters, default values, and so on. Soon we'll see that.
18
+
>>>>>>> 468e3552884851fcef331fbdfd58096652964b5f
8
19
9
20
## Array destructuring
10
21
11
-
An example of how the array is destructured into variables:
22
+
Here's an example of how an array is destructured into variables:
12
23
13
24
```js
14
25
// we have an array with the name and surname
15
-
let arr = ["Ilya", "Kantor"]
26
+
let arr = ["John", "Smith"]
16
27
17
28
*!*
18
29
// destructuring assignment
19
30
let [firstName, surname] = arr;
20
31
*/!*
21
32
22
-
alert(firstName); //Ilya
23
-
alert(surname); //Kantor
33
+
alert(firstName); //John
34
+
alert(surname); //Smith
24
35
```
25
36
26
37
Now we can work with variables instead of array members.
27
38
28
39
It looks great when combined with `split` or other array-returning methods:
29
40
30
-
```js
31
-
let [firstName, surname] ="Ilya Kantor".split('');
41
+
```js run
42
+
let [firstName, surname] ="John Smith".split('');
43
+
alert(firstName); // John
44
+
alert(surname); // Smith
32
45
```
33
46
47
+
As you can see, the syntax is simple. There are several peculiar details though. Let's see more examples, to better understand it.
48
+
34
49
````smart header="\"Destructuring\" does not mean \"destructive\"."
35
50
It's called "destructuring assignment," because it "destructurizes" by copying items into variables. But the array itself is not modified.
36
51
@@ -65,26 +80,25 @@ In the code above, the second element of the array is skipped, the third one is
65
80
let [a, b, c] = "abc"; // ["a", "b", "c"]
66
81
let [one, two, three] = new Set([1, 2, 3]);
67
82
```
68
-
83
+
That works, because internally a destructuring assignment works by iterating over the right value. It's kind of syntax sugar for calling `for..of` over the value to the right of `=` and assigning the values.
69
84
````
70
85
71
86
72
87
````smart header="Assign to anything at the left-side"
In the previous chapter we saw the [Object.entries(obj)](mdn:js/Object/entries) method.
89
103
90
104
We can use it with destructuring to loop over keys-and-values of an object:
@@ -103,62 +117,85 @@ for (let [key, value] of Object.entries(user)) {
103
117
}
104
118
```
105
119
106
-
...And the same for a map:
120
+
The similar code for a `Map` is simpler, as it's iterable:
107
121
108
122
```js run
109
123
let user = new Map();
110
124
user.set("name", "John");
111
125
user.set("age", "30");
112
126
113
127
*!*
128
+
<<<<<<< HEAD
114
129
for (let [key, value] of user.entries()) {
130
+
=======
131
+
// Map iterates as [key, value] pairs, very convenient for destructuring
132
+
for (let [key, value] of user) {
133
+
>>>>>>> 468e3552884851fcef331fbdfd58096652964b5f
115
134
*/!*
116
135
alert(`${key}:${value}`); // name:John, then age:30
117
136
}
118
137
```
119
138
````
120
139
121
-
```smart header="Swap variables trick"
122
-
A well-known trick for swapping values of two variables:
140
+
````smart header="Swap variables trick"
141
+
There's a well-known trick for swapping values of two variables using a destructuring assignment:
123
142
124
143
```js run
125
144
let guest = "Jane";
126
145
let admin = "Pete";
127
146
128
-
// Swap values: make guest=Pete, admin=Jane
147
+
// Let's swap the values: make guest=Pete, admin=Jane
148
+
*!*
129
149
[guest, admin] = [admin, guest];
150
+
*/!*
130
151
131
152
alert(`${guest} ${admin}`); // Pete Jane (successfully swapped!)
132
153
```
133
154
134
155
Here we create a temporary array of two variables and immediately destructure it in swapped order.
135
156
136
157
We can swap more than two variables this way.
137
-
158
+
````
138
159
139
160
### The rest '...'
140
161
141
-
If we want not just to get first values, but also to gather all that follows -- we can add one more parameter that gets "the rest" using three dots `"..."`:
162
+
Usually, if the array is longer when the list at the left, the "extra" items are omitted.
163
+
164
+
For example, here only two items are taken, and the rest is just ignored:
142
165
143
166
```js run
144
-
let [name1, name2, *!*...rest*/!*] = ["Julius", "Caesar", *!*"Consul", "of the Roman Republic"*/!*];
167
+
let [name1, name2] = ["Julius", "Caesar", "Consul", "of the Roman Republic"];
145
168
146
169
alert(name1); // Julius
147
170
alert(name2); // Caesar
171
+
// Furher items aren't assigned anywhere
172
+
```
173
+
174
+
If we'd like also to gather all that follows -- we can add one more parameter that gets "the rest" using three dots `"..."`:
175
+
176
+
```js run
177
+
let [name1, name2, *!*...rest*/!*] = ["Julius", "Caesar", *!*"Consul", "of the Roman Republic"*/!*];
148
178
149
179
*!*
150
-
//Note that type of `rest` is Array.
180
+
//rest is arrayofitems, starting from the 3rd one
151
181
alert(rest[0]); // Consul
152
182
alert(rest[1]); // of the Roman Republic
153
183
alert(rest.length); // 2
154
184
*/!*
155
185
```
156
186
157
-
The value of `rest` is the array of the remaining array elements. We can use any other variable name in place of `rest`, just make sure it has three dots before it and goes last in the destructuring assignment.
187
+
The value of `rest` is the array of the remaining array elements.
188
+
189
+
We can use any other variable name in place of `rest`, just make sure it has three dots before it and goes last in the destructuring assignment.
190
+
191
+
```js run
192
+
let [name1, name2, *!*...titles*/!*] = ["Julius", "Caesar", "Consul", "of the Roman Republic"];
193
+
// now titles = ["Consul", "of the Roman Republic"]
194
+
```
158
195
159
196
### Default values
160
197
161
-
If there are fewer values in the array than variables in the assignment, there will be no error. Absent values are considered undefined:
198
+
If the array is shorter than the list of variables at the left, there'll be no errors. Absent values are considered undefined:
Default values can be more complex expressions or even function calls. They are evaluated only if the value is not provided.
185
222
186
-
For instance, here we use the `prompt` function for two defaults. But it will run only for the missing one:
223
+
For instance, here we use the `prompt` function for two defaults:
187
224
188
225
```js run
189
226
// runs only prompt for surname
@@ -193,7 +230,7 @@ alert(name); // Julius (from array)
193
230
alert(surname); // whatever prompt gets
194
231
```
195
232
196
-
233
+
Please note: the `prompt` will run only for the missing value (`surname`).
197
234
198
235
## Object destructuring
199
236
@@ -205,7 +242,7 @@ The basic syntax is:
205
242
let {var1, var2} = {var1:…, var2:…}
206
243
```
207
244
208
-
We have an existing object at the right side, that we want to split into variables. The left side contains a "pattern" for corresponding properties. In the simple case, that's a list of variable names in `{...}`.
245
+
We should have an existing object at the right side, that we want to split into variables. The left side contains an object-like "pattern" for corresponding properties. In the simplest case, that's a list of variable names in `{...}`.
209
246
210
247
For instance:
211
248
@@ -225,7 +262,9 @@ alert(width); // 100
225
262
alert(height); // 200
226
263
```
227
264
228
-
Properties `options.title`, `options.width` and `options.height` are assigned to the corresponding variables. The order does not matter. This works too:
265
+
Properties `options.title`, `options.width` and `options.height` are assigned to the corresponding variables.
The pattern on the left side may be more complex and specify the mapping between properties and variables.
236
275
237
-
If we want to assign a property to a variable with another name, for instance, `options.width`to go into the variable named `w`, then we can set it using a colon:
276
+
If we want to assign a property to a variable with another name, for instance, make `options.width` go into the variable named `w`, then we can set the variable name using a colon:
Copy file name to clipboardExpand all lines: 1-js/06-advanced-functions/10-bind/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
@@ -247,7 +247,7 @@ The call to `mul.bind(null, 2)` creates a new function `double` that passes call
247
247
248
248
That's called [partial function application](https://en.wikipedia.org/wiki/Partial_application) -- we create a new function by fixing some parameters of the existing one.
249
249
250
-
Please note that here we actually don't use `this` here. But `bind` requires it, so we must put in something like `null`.
250
+
Please note that we actually don't use `this` here. But `bind` requires it, so we must put in something like `null`.
251
251
252
252
The function `triple` in the code below triples the value:
Copy file name to clipboardExpand all lines: 1-js/99-js-misc/03-currying-partials/article.md
+4-12Lines changed: 4 additions & 12 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -155,7 +155,7 @@ function curried(...args) {
155
155
if (args.length>=func.length) { // (1)
156
156
returnfunc.apply(this, args);
157
157
} else {
158
-
returnfunctionpass(...args2) { // (2)
158
+
returnfunction(...args2) { // (2)
159
159
returncurried.apply(this, args.concat(args2));
160
160
}
161
161
}
@@ -164,18 +164,10 @@ function curried(...args) {
164
164
165
165
When we run it, there are two `if` execution branches:
166
166
167
-
1.Call now: if passed `args` count is the same as the original function has in its definition (`func.length`) or longer, then just pass the call to it.
168
-
2.Get a partial: otherwise, `func`is not called yet. Instead, another wrapper `pass`is returned, that will re-apply `curried` providing previous arguments together with the new ones. Then on a new call, again, we'll get either a new partial (if not enough arguments) or, finally, the result.
167
+
1.If passed `args` count is the same or more than the original function has in its definition (`func.length`) , then just pass the call to it using `func.apply`.
168
+
2.Otherwise, get a partial: we don't call `func`just yet. Instead, another wrapper is returned, that will re-apply `curried` providing previous arguments together with the new ones.
169
169
170
-
For instance, let's see what happens in the case of `sum(a, b, c)`. Three arguments, so `sum.length = 3`.
171
-
172
-
For the call `curried(1)(2)(3)`:
173
-
174
-
1. The first call `curried(1)` remembers `1` in its Lexical Environment, and returns a wrapper `pass`.
175
-
2. The wrapper `pass` is called with `(2)`: it takes previous args (`1`), concatenates them with what it got `(2)` and calls `curried(1, 2)` with them together. As the argument count is still less than 3, `curry` returns `pass`.
176
-
3. The wrapper `pass` is called again with `(3)`, for the next call `pass(3)` takes previous args (`1`, `2`) and adds `3` to them, making the call `curried(1, 2, 3)` -- there are `3` arguments at last, they are given to the original function.
177
-
178
-
If that's still not obvious, just trace the calls sequence in your mind or on paper.
170
+
Then, if we call it, again, we'll get either a new partial (if not enough arguments) or, finally, the result.
179
171
180
172
```smart header="Fixed-length functions only"
181
173
The currying requires the function to have a fixed number of arguments.
0 commit comments