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
-
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.
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.
10
10
11
-
Em segundo lugar, o nome do visitante atual:
11
+
## O nome do visitante atual
12
12
13
13
```js
14
14
let currentUserName ="John";
15
15
```
16
16
17
-
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.
18
18
19
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.
20
20
21
-
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
+62-28Lines changed: 62 additions & 28 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,5 +1,5 @@
1
1
2
-
# Polyfills
2
+
# Polyfills and transpilers
3
3
4
4
The JavaScript language steadily evolves. New proposals to the language appear regularly, they are analyzed and, if considered worthy, are appended to the list at <https://tc39.github.io/ecma262/> and then progress to the [specification](http://www.ecma-international.org/publications/standards/Ecma-262.htm).
5
5
@@ -9,50 +9,84 @@ So it's quite common for an engine to implement only the part of the standard.
9
9
10
10
A good page to see the current state of support for language features is <https://kangax.github.io/compat-table/es6/> (it's big, we have a lot to study yet).
11
11
12
-
## Babel
12
+
As programmers, we'd like to use most recent features. The more good stuff - the better!
13
13
14
-
When we use modern features of the language, some engines may fail to support such code. Just as said, not all features are implemented everywhere.
14
+
From the other hand, how to make out modern code work on older engines that don't understand recent features yet?
15
15
16
-
Here Babel comes to the rescue.
16
+
There are two tools for that:
17
17
18
-
[Babel](https://babeljs.io) is a [transpiler](https://en.wikipedia.org/wiki/Source-to-source_compiler). It rewrites modern JavaScript code into the previous standard.
18
+
1. Transpilers.
19
+
2. Polyfills.
19
20
20
-
Actually, there are two parts in Babel:
21
+
Here, in this chapter, our purpose is to get the gist of how they work, and their place in web development.
21
22
22
-
1. First, the transpiler program, which rewrites the code. The developer runs it on their own computer. It rewrites the code into the older standard. And then the code is delivered to the website for users. Modern project build systems like [webpack](http://webpack.github.io/) provide means to run transpiler automatically on every code change, so that it's very easy to integrate into development process.
23
+
## Transpilers
23
24
24
-
2. Second, the polyfill.
25
+
A [transpiler](https://en.wikipedia.org/wiki/Source-to-source_compiler) is a special piece of software that can parse ("read and understand") modern code, and rewrite it using older syntax constructs, so that the result would be the same.
25
26
26
-
New language features may include not only syntax constructs, but also built-in functions.
27
-
The transpiler rewrites the code, transforming syntax constructs into older ones. But as for new built-in functions, we need to implement them. JavaScript is a highly dynamic language, scripts may add/modify any functions, so that they behave according to the modern standard.
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
-
There's a term "polyfill" for scripts that "fill in" the gap and add missing implementations.
29
+
A transpiler would analyze our code and rewrite `height ?? 100` into `(height !== undefined && height !== null) ? height : 100`.
30
30
31
-
Two interesting polyfills are:
32
-
-[babel polyfill](https://babeljs.io/docs/usage/polyfill/) that supports a lot, but is big.
33
-
-[polyfill.io](http://polyfill.io) service that allows to load/construct polyfills on-demand, depending on the features we need.
31
+
```js
32
+
// before running the transpiler
33
+
height = height ??100;
34
34
35
-
So, we need to setup the transpiler and add the polyfill for old engines to support modern features.
If we orient towards modern engines and do not use features except those supported everywhere, then we don't need to use Babel.
39
+
Now the rewritten code is suitable for older JavaScript engines.
38
40
39
-
## Examples in the tutorial
41
+
Usually, a developer runs the transpiler on their own computer, and then deploys the transpiled code to the server.
40
42
43
+
Speaking of names, [Babel](https://babeljs.io) is one of the most prominent transpilers out there.
41
44
42
-
````online
43
-
Most examples are runnable at-place, like this:
45
+
Modern project build systems, such as [webpack](http://webpack.github.io/), provide means to run transpiler automatically on every code change, so it's very easy to integrate into development process.
44
46
45
-
```js run
46
-
alert('Press the "Play" button in the upper-right corner to run');
47
-
```
47
+
## Polyfills
48
+
49
+
New language features may include not only syntax constructs and operators, but also built-in functions.
50
+
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`.
48
52
49
-
Examples that use modern JS will work only if your browser supports it.
50
-
````
53
+
In some (very outdated) JavaScript engines, there's no `Math.trunc`, so such code will fail.
51
54
52
-
```offline
53
-
As you're reading the offline version, examples are not runnable. But they usually work :)
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.
56
+
57
+
A script that updates/adds new functions is called "polyfill". It "fills in" the gap and adds missing implementations.
58
+
59
+
For this particular case, the polyfill for `Math.trunc` is a script that implements it, like this:
60
+
61
+
```js
62
+
if (!Math.trunc) { // if no such function
63
+
// implement it
64
+
Math.trunc=function(number) {
65
+
// Math.ceil and Math.floor exist even in ancient JavaScript engines
66
+
// they are covered later in the tutorial
67
+
return number <0?Math.ceil(number) :Math.floor(number);
68
+
};
69
+
}
54
70
```
55
71
56
-
[Chrome Canary](https://www.google.com/chrome/browser/canary.html) is good for all examples, but other modern browsers are mostly fine too.
72
+
JavaScript is a highly dynamic language, scripts may add/modify any functions, even including built-in ones.
73
+
74
+
Two interesting libraries of polyfills are:
75
+
- [core js](https://github.com/zloirock/core-js) that supports a lot, allows to include only needed features.
76
+
- [polyfill.io](http://polyfill.io) service that provides a script with polyfills, depending on the features and user's browser.
77
+
78
+
79
+
## Summary
80
+
81
+
In this chapter we'd like to motivate you to study modern and even "bleeding-edge" langauge features, even if they aren't yet well-supported by JavaScript engines.
82
+
83
+
Just don't forget to use transpiler (if using modern syntax or operators) and polyfills (to add functions that may be missing). And they'll ensure that the code works.
84
+
85
+
For example, later when you're familiar with JavaScript, you can setup a code build system based on [webpack](http://webpack.github.io/) with [babel-loader](https://github.com/babel/babel-loader) plugin.
86
+
87
+
Good resources that show the current state of support for various features:
88
+
- <https://kangax.github.io/compat-table/es6/> - for pure JavaScript.
89
+
- <https://caniuse.com/> - for browser-related functions.
90
+
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.
57
92
58
-
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.
The solution has a time complexety of [O(n<sup>2</sup>)](https://en.wikipedia.org/wiki/Big_O_notation). In other words, if we increase the array size 2 times, the algorithm will work 4 times longer.
60
+
The solution has a time complexity of [O(n<sup>2</sup>)](https://en.wikipedia.org/wiki/Big_O_notation). In other words, if we increase the array size 2 times, the algorithm will work 4 times longer.
61
61
62
62
For big arrays (1000, 10000 or more items) such algorithms can lead to a serious sluggishness.
Copy file name to clipboardExpand all lines: 1-js/05-data-types/04-array/article.md
+20-20Lines changed: 20 additions & 20 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,13 +203,13 @@ 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
210
210
```
211
211
212
-
...But what makes arrays really special is their internal representation. The engine tries to store its elements in the contiguous memory area, one after another, just as depicted on the illustrations in this chapter, and there are other optimizations as well, to make arrays work really fast.
212
+
...But what makes arrays really special is their internal representation. The engine tries to store its elements in the contiguous memory area, one after another, just as depicted on the illustrations in this chapter, and there are other optimizations as well, to make arrays work really fast.
213
213
214
214
But they all break if we quit working with an array as with an "ordered collection" and start working with it as if it were a regular object.
215
215
@@ -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/05-data-types/08-weakmap-weakset/article.md
+4-3Lines changed: 4 additions & 3 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -207,7 +207,7 @@ alert(cache.size); // 1 (Ouch! The object is still in cache, taking memory!)
207
207
208
208
For multiple calls of `process(obj)` with the same object, it only calculates the result the first time, and then just takes it from `cache`. The downside is that we need to clean `cache` when the object is not needed any more.
209
209
210
-
If we replace `Map` with `WeakMap`, then this problem disappears. The cached result will be removed from memory automatically after the object gets garbage collected.
210
+
If we replace `Map` with `WeakMap`, then this problem disappears. The cached result will be removed from memory automatically after the object gets garbage collected.
211
211
212
212
```js run
213
213
// 📁 cache.js
@@ -284,7 +284,8 @@ The most notable limitation of `WeakMap` and `WeakSet` is the absence of iterati
284
284
285
285
`WeakSet` is `Set`-like collection that stores only objects and removes them once they become inaccessible by other means.
286
286
287
-
It's main advantages are that they have weak reference to objects, so they can easily be removed by garbage colector.
288
-
That comes at the cost of not having support for `clear`, `size`, `keys`, `values` ...
287
+
Their main advantages are that they have weak reference to objects, so they can easily be removed by garbage collector.
288
+
289
+
That comes at the cost of not having support for `clear`, `size`, `keys`, `values`...
289
290
290
291
`WeakMap` and `WeakSet` are used as "secondary" data structures in addition to the "primary" object storage. Once the object is removed from the primary storage, if it is only found as the key of `WeakMap` or in a `WeakSet`, it will be cleaned up automatically.
0 commit comments