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
Primeiro, a variável para o nome do nosso planeta.
1
+
## A variável para o nosso planeta
2
2
3
3
Isso é simples:
4
4
5
5
```js
6
6
let ourPlanetName = "Earth";
7
7
```
8
8
9
-
<<<<<<< HEAD
10
-
Note que poderíamos usar um nome mais curto, `planet`, mas pode não ser óbvio a que planeta se refere. É bom ser mais detalhado. Pelo menos até a variável isNotTooLong.
11
-
=======
12
-
Note, we could use a shorter name `planet`, but it might not be obvious what planet it refers to. It's nice to be more verbose. At least until the variable isNotTooLong.
13
-
>>>>>>> c56e6a57ac3497aab77128c5bfca13513980709b
9
+
Note que poderíamos usar um nome mais curto, `planet`, mas pode não ser óbvio a que planeta se refere. É bom ser mais detalhado. Pelo menos até a variável naoForDemasiadoLonga.
14
10
15
-
Em segundo lugar, o nome do visitante atual:
11
+
## O nome do visitante atual
16
12
17
13
```js
18
14
let currentUserName = "John";
19
15
```
20
16
21
-
Novamente, nós poderíamos encurtar isso para `userName` se tivermos certeza que o usuário é atual.
17
+
Novamente, nós poderíamos encurtar isso para `userName` se tivermos a certeza de que o usuário é o atual.
22
18
23
19
Os editores modernos e o autocomplete facilitam a escrita de nomes longos de variáveis. Não salve neles. Um nome com 3 palavras é o suficiente.
24
20
25
-
E se o seu editor não possui autocompletar corretamente, obtenha [um novo](/code-editors).
21
+
E se o seu editor não possui autocompletar corretamente, obtenha [um novo](/code-editors).
Copy file name to clipboardExpand all lines: 1-js/03-code-quality/06-polyfills/article.md
-22Lines changed: 0 additions & 22 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -26,17 +26,6 @@ A [transpiler](https://en.wikipedia.org/wiki/Source-to-source_compiler) is a spe
26
26
27
27
E.g. JavaScript before year 2020 didn't have the "nullish coalescing operator" `??`. So, if a visitor uses an outdated browser, it may fail to understand the code like `height = height ?? 100`.
28
28
29
-
<<<<<<< HEAD
30
-
There's a term "polyfill" for scripts that "fill in" the gap and add missing implementations.
31
-
32
-
Two interesting polyfills are:
33
-
- [babel polyfill](https://babeljs.io/docs/usage/polyfill/) that supports a lot, but is big.
34
-
- [polyfill.io](http://polyfill.io) service that allows to load/construct polyfills on-demand, depending on the features we need.
35
-
36
-
So, we need to setup the transpiler and add the polyfill for old engines to support modern features.
37
-
38
-
If we orient towards modern engines and do not use features except those supported everywhere, then we don't need to use Babel.
39
-
=======
40
29
A transpiler would analyze our code and rewrite `height ?? 100` into `(height !== undefined && height !== null) ? height : 100`.
Now the rewritten code is suitable for older JavaScript engines.
52
40
@@ -64,15 +52,6 @@ For example, `Math.trunc(n)` is a function that "cuts off" the decimal part of a
64
52
65
53
In some (very outdated) JavaScript engines, there's no `Math.trunc`, so such code will fail.
66
54
67
-
<<<<<<< HEAD
68
-
```offline
69
-
As you're reading the offline version, examples are not runnable. But they usually work :)
70
-
```
71
-
72
-
[Chrome Canary](https://www.google.com/chrome/browser/canary.html) is good for all examples, but other modern browsers are mostly fine too.
73
-
74
-
Note that on production we can use Babel to translate the code into suitable for less recent browsers, so there will be no such limitation, the code will run everywhere.
75
-
=======
76
55
As we're talking about new functions, not syntax changes, there's no need to transpile anything here. We just need to declare the missing function.
77
56
78
57
A script that updates/adds new functions is called "polyfill". It "fills in" the gap and adds missing implementations.
@@ -111,4 +90,3 @@ Good resources that show the current state of support for various features:
111
90
112
91
P.S. Google Chrome is usually the most up-to-date with language features, try it if a tutorial demo fails. Most tutorial demos work with any modern browser though.
Copy file name to clipboardExpand all lines: 1-js/05-data-types/04-array/article.md
+19-19Lines changed: 19 additions & 19 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,12 +1,12 @@
1
-
# Arrays
1
+
# Arrays
2
2
3
3
Objects allow you to store keyed collections of values. That's fine.
4
4
5
-
But quite often we find that we need an *ordered collection*, where we have a 1st, a 2nd, a 3rd element and so on. For example, we need that to store a list of something: users, goods, HTML elements etc.
5
+
But quite often we find that we need an *ordered collection*, where we have a 1st, a 2nd, a 3rd element and so on. For example, we need that to store a list of something: users, goods, HTML elements etc.
6
6
7
7
It is not convenient to use an object here, because it provides no methods to manage the order of elements. We can’t insert a new property “between” the existing ones. Objects are just not meant for such use.
8
8
9
-
There exists a special data structure named `Array`, to store ordered collections.
9
+
There exists a special data structure named `Array`, to store ordered collections.
10
10
11
11
## Declaration
12
12
@@ -81,10 +81,10 @@ arr[3](); // hello
81
81
82
82
````smart header="Trailing comma"
83
83
An array, just like an object, may end with a comma:
84
-
```js
84
+
```js
85
85
let fruits = [
86
-
"Apple",
87
-
"Orange",
86
+
"Apple",
87
+
"Orange",
88
88
"Plum"*!*,*/!*
89
89
];
90
90
```
@@ -95,7 +95,7 @@ The "trailing comma" style makes it easier to insert/remove items, because all l
95
95
96
96
## Methods pop/push, shift/unshift
97
97
98
-
A [queue](https://en.wikipedia.org/wiki/Queue_(abstract_data_type)) is one of most common uses of an array. In computer science, this means an ordered collection of elements which supports two operations:
98
+
A [queue](https://en.wikipedia.org/wiki/Queue_(abstract_data_type)) is one of the most common uses of an array. In computer science, this means an ordered collection of elements which supports two operations:
99
99
100
100
- `push` appends an element to the end.
101
101
- `shift` get an element from the beginning, advancing the queue, so that the 2nd element becomes the 1st.
@@ -106,7 +106,7 @@ Arrays support both operations.
106
106
107
107
In practice we need it very often. For example, a queue of messages that need to be shown on-screen.
108
108
109
-
There's another use case for arrays -- the data structure named [stack](https://en.wikipedia.org/wiki/Stack_(abstract_data_type)).
109
+
There's another use case for arrays -- the data structure named [stack](https://en.wikipedia.org/wiki/Stack_(abstract_data_type)).
110
110
111
111
It supports two operations:
112
112
@@ -121,7 +121,7 @@ A stack is usually illustrated as a pack of cards: new cards are added to the to
121
121
122
122
For stacks, the latest pushed item is received first, that's also called LIFO (Last-In-First-Out) principle. For queues, we have FIFO (First-In-First-Out).
123
123
124
-
Arrays in JavaScript can work both as a queue and as a stack. They allow you to add/remove elements both to/from the beginning or the end.
124
+
Arrays in JavaScript can work both as a queue and as a stack. They allow you to add/remove elements both to/from the beginning or the end.
125
125
126
126
In computer science the data structure that allows this, is called [deque](https://en.wikipedia.org/wiki/Double-ended_queue).
127
127
@@ -189,7 +189,7 @@ alert( fruits );
189
189
190
190
## Internals
191
191
192
-
An array is a special kind of object. The square brackets used to access a property `arr[0]` actually come from the object syntax. Numbers are used as keys.
192
+
An array is a special kind of object. The square brackets used to access a property `arr[0]` actually come from the object syntax. That's essentially the same as `obj[key]`, where `arr` is the object, while numbers are used as keys.
193
193
194
194
They extend objects providing special methods to work with ordered collections of data and also the `length` property. But at the core it's still an object.
195
195
@@ -203,7 +203,7 @@ let fruits = ["Banana"]
203
203
let arr = fruits; // copy by reference (two variables reference the same array)
204
204
205
205
alert( arr === fruits ); // true
206
-
206
+
207
207
arr.push("Pear"); // modify the array by reference
208
208
209
209
alert( fruits ); // Banana, Pear - 2 items now
@@ -229,7 +229,7 @@ But the engine will see that we're working with the array as with a regular obje
229
229
230
230
The ways to misuse an array:
231
231
232
-
- Add a non-numeric property like `arr.test = 5`.
232
+
- Add a non-numeric property like `arr.test = 5`.
233
233
- Make holes, like: add `arr[0]` and then `arr[1000]` (and nothing between them).
234
234
- Fill the array in the reverse order, like `arr[1000]`, `arr[999]` and so on.
235
235
@@ -296,7 +296,7 @@ let fruits = ["Apple", "Orange", "Plum"];
296
296
297
297
// iterates over array elements
298
298
for (let fruit of fruits) {
299
-
alert( fruit );
299
+
alert( fruit );
300
300
}
301
301
```
302
302
@@ -320,7 +320,7 @@ But that's actually a bad idea. There are potential problems with it:
320
320
321
321
There are so-called "array-like" objects in the browser and in other environments, that *look like arrays*. That is, they have `length` and indexes properties, but they may also have other non-numeric properties and methods, which we usually don't need. The `for..in` loop will list them though. So if we need to work with array-like objects, then these "extra" properties can become a problem.
322
322
323
-
2. The `for..in` loop is optimized for generic objects, not arrays, and thus is 10-100 times slower. Of course, it's still very fast. The speedup may only matter in bottlenecks or seem irrelevant. But still we should be aware of the difference.
323
+
2. The `for..in` loop is optimized for generic objects, not arrays, and thus is 10-100 times slower. Of course, it's still very fast. The speedup may only matter in bottlenecks. But still we should be aware of the difference.
324
324
325
325
Generally, we shouldn't use `for..in` for arrays.
326
326
@@ -338,7 +338,7 @@ fruits[123] = "Apple";
338
338
alert( fruits.length ); // 124
339
339
```
340
340
341
-
Note that we usually don't use arrays like that.
341
+
Note that we usually don't use arrays like that.
342
342
343
343
Another interesting thing about the `length` property is that it's writable.
344
344
@@ -385,7 +385,7 @@ To evade such surprises, we usually use square brackets, unless we really know w
385
385
386
386
## Multidimensional arrays
387
387
388
-
Arrays can have items that are also arrays. We can use it for multidimensional arrays, to store matrices:
388
+
Arrays can have items that are also arrays. We can use it for multidimensional arrays, for example to store matrices:
389
389
390
390
```js run
391
391
let matrix = [
@@ -394,7 +394,7 @@ let matrix = [
394
394
[7, 8, 9]
395
395
];
396
396
397
-
alert( matrix[1][1] ); // the central element
397
+
alert( matrix[1][1] ); // 5, the central element
398
398
```
399
399
400
400
## toString
@@ -492,15 +492,15 @@ Array is a special kind of object, suited to storing and managing ordered data i
492
492
493
493
The call to `new Array(number)` creates an array with the given length, but without elements.
494
494
495
-
- The `length` property is the array length or, to be precise, its last numeric index plus one. It is auto-adjusted by array methods.
495
+
- The `length` property is the array length or, to be precise, its last numeric index plus one. It is auto-adjusted by array methods.
496
496
- If we shorten `length` manually, the array is truncated.
497
497
498
498
We can use an array as a deque with the following operations:
499
499
500
500
- `push(...items)` adds `items` to the end.
501
501
- `pop()` removes the element from the end and returns it.
502
502
- `shift()` removes the element from the beginning and returns it.
503
-
- `unshift(...items)` adds items to the beginning.
503
+
- `unshift(...items)` adds `items` to the beginning.
504
504
505
505
To loop over the elements of the array:
506
506
- `for (let i=0; i<arr.length; i++)` -- works fastest, old-browser-compatible.
Copy file name to clipboardExpand all lines: 1-js/09-classes/04-private-protected-properties-methods/article.md
+15-35Lines changed: 15 additions & 35 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -48,16 +48,16 @@ So, all we need to use an object is to know its external interface. We may be co
48
48
49
49
That was a general introduction.
50
50
51
-
In JavaScript, there are three types of properties and members:
51
+
In JavaScript, there are two types of object fields (properties and methods):
52
52
53
53
- Public: accessible from anywhere. They comprise the external interface. Until now we were only using public properties and methods.
54
54
- Private: accessible only from inside the class. These are for the internal interface.
55
55
56
-
In many other languages there also exist "protected" fields: accessible only from inside the class and those extending it. They are also useful for the internal interface. They are in a sense more widespread than private ones, because we usually want inheriting classes to gain access to properly do the extension.
56
+
In many other languages there also exist "protected" fields: accessible only from inside the class and those extending it (like private, but plus access from inheriting classes). They are also useful for the internal interface. They are in a sense more widespread than private ones, because we usually want inheriting classes to gain access to them.
57
57
58
58
Protected fields are not implemented in JavaScript on the language level, but in practice they are very convenient, so they are emulated.
59
59
60
-
In the next step we'll make a coffee machine in JavaScript with all these types of properties. A coffee machine has a lot of details, we won't model them to stay simple (though we could).
60
+
Now we'll make a coffee machine in JavaScript with all these types of properties. A coffee machine has a lot of details, we won't model them to stay simple (though we could).
61
61
62
62
## Protecting "waterAmount"
63
63
@@ -87,7 +87,7 @@ Let's change `waterAmount` property to protected to have more control over it. F
87
87
88
88
**Protected properties are usually prefixed with an underscore `_`.**
89
89
90
-
That is not enforced on the language level, but there's a convention that such properties and methods should not be accessed from the outside. Most programmers follow it.
90
+
That is not enforced on the language level, but there's a well-known convention between programmers that such properties and methods should not be accessed from the outside.
91
91
92
92
So our property will be called `_waterAmount`:
93
93
@@ -166,16 +166,16 @@ class CoffeeMachine {
166
166
}
167
167
168
168
*!*getWaterAmount()*/!* {
169
-
return this.waterAmount;
169
+
return this._waterAmount;
170
170
}
171
171
}
172
172
173
173
new CoffeeMachine().setWaterAmount(100);
174
174
```
175
175
176
-
That looks a bit longer, but functions are more flexible. They can accept multiple arguments (even if we don't need them right now). So, for the future, just in case we need to refactor something, functions are a safer choise.
176
+
That looks a bit longer, but functions are more flexible. They can accept multiple arguments (even if we don't need them right now).
177
177
178
-
Surely, there's a tradeoff. On the other hand, get/set syntax is shorter, so ultimately there's no strict rule, it's up to you to decide.
178
+
On the other hand, get/set syntax is shorter, so ultimately there's no strict rule, it's up to you to decide.
179
179
````
180
180
181
181
```smart header="Protected fields are inherited"
@@ -192,9 +192,9 @@ There's a finished JavaScript proposal, almost in the standard, that provides la
192
192
193
193
Privates should start with `#`. They are only accessible from inside the class.
194
194
195
-
For instance, here we add a private `#waterLimit` property and extract the water-checking logic into a separate method:
195
+
For instance, here's a private `#waterLimit` property and the water-checking private method `#checkWater`:
196
196
197
-
```js
197
+
```js run
198
198
class CoffeeMachine {
199
199
*!*
200
200
#waterLimit = 200;
@@ -207,39 +207,19 @@ class CoffeeMachine {
207
207
}
208
208
*/!*
209
209
210
-
<<<<<<< HEAD
211
-
_waterAmount = 0;
212
-
213
-
set waterAmount(value) {
214
-
*!*
215
-
this.#checkWater(value);
216
-
*/!*
217
-
this._waterAmount = value;
218
-
}
219
-
220
-
get waterAmount() {
221
-
return this.waterAmount;
222
-
=======
223
210
setWaterAmount(value) {
224
211
this.#waterLimit = this.#fixWaterAmount(value);
225
-
>>>>>>> c56e6a57ac3497aab77128c5bfca13513980709b
226
212
}
227
213
228
214
}
229
215
230
216
let coffeeMachine = new CoffeeMachine();
231
217
232
218
*!*
233
-
<<<<<<< HEAD
234
-
coffeeMachine.#checkWater(); // Error
235
-
=======
236
219
// can't access privates from outside of the class
237
220
coffeeMachine.#fixWaterAmount(123); // Error
238
-
>>>>>>> c56e6a57ac3497aab77128c5bfca13513980709b
239
221
coffeeMachine.#waterLimit = 1000; // Error
240
222
*/!*
241
-
242
-
coffeeMachine.waterAmount = 100; // Works
243
223
```
244
224
245
225
On the language level, `#` is a special sign that the field is private. We can't access it from outside or from inheriting classes.
@@ -285,17 +265,17 @@ class MegaCoffeeMachine extends CoffeeMachine {
285
265
286
266
In many scenarios such limitation is too severe. If we extend a `CoffeeMachine`, we may have legitimate reasons to access its internals. That's why protected fields are used more often, even though they are not supported by the language syntax.
287
267
288
-
````warn
268
+
````warn header="Private fields are not available as this[name]"
289
269
Private fields are special.
290
270
291
-
Remember, usually we can access fields by this[name]:
271
+
As we know, usually we can access fields using `this[name]`:
292
272
293
273
```js
294
274
class User {
295
275
...
296
276
sayHi() {
297
277
let fieldName = "name";
298
-
alert(`Hello, ${this[fieldName]}`);
278
+
alert(`Hello, ${*!*this[fieldName]*/!*}`);
299
279
}
300
280
}
301
281
```
@@ -321,11 +301,11 @@ Protection for users, so that they don't shoot themselves in the foot
321
301
Supportable
322
302
: The situation in programming is more complex than with a real-life coffee machine, because we don't just buy it once. The code constantly undergoes development and improvement.
323
303
324
-
**If we strictly delimit the internal interface, then the developer of the class can freely change its internal properties and methods, even without informing the users..**
304
+
**If we strictly delimit the internal interface, then the developer of the class can freely change its internal properties and methods, even without informing the users.**
325
305
326
-
It's much easier to develop, if you know that certain methods can be renamed, their parameters can be changed, and even removed, because no external code depends on them.
306
+
If you're a developer of such class, it's great to know that private methods can be safely renamed, their parameters can be changed, and even removed, because no external code depends on them.
327
307
328
-
For users, when a new version comes out, it may be a total overhaul, but still simple to upgrade if the external interface is the same.
308
+
For users, when a new version comes out, it may be a total overhaul internally, but still simple to upgrade if the external interface is the same.
329
309
330
310
Hiding complexity
331
311
: People adore using things that are simple. At least from outside. What's inside is a different thing.
0 commit comments