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/02-first-steps/04-variables/2-declare-variables/solution.md
+4Lines changed: 4 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -6,7 +6,11 @@ Isso é simples:
6
6
let ourPlanetName ="Earth";
7
7
```
8
8
9
+
<<<<<<< HEAD
9
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.
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,23 +9,24 @@ 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
+
<<<<<<< HEAD
29
30
There's a term "polyfill" for scripts that "fill in" the gap and add missing implementations.
30
31
31
32
Two interesting polyfills are:
@@ -35,24 +36,79 @@ Actually, there are two parts in Babel:
35
36
So, we need to setup the transpiler and add the polyfill for old engines to support modern features.
36
37
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
+
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.
44
52
45
-
```js run
46
-
alert('Press the "Play" button in the upper-right corner to run');
47
-
```
53
+
Usually, a developer runs the transpiler on their own computer, and then deploys the transpiled code to the server.
54
+
55
+
Speaking of names, [Babel](https://babeljs.io) is one of the most prominent transpilers out there.
56
+
57
+
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.
58
+
59
+
## Polyfills
48
60
49
-
Examples that use modern JS will work only if your browser supports it.
50
-
````
61
+
New language features may include not only syntax constructs and operators, but also built-in functions.
51
62
63
+
For example, `Math.trunc(n)` is a function that "cuts off" the decimal part of a number, e.g `Math.trunc(1.23) =1`.
64
+
65
+
In some (very outdated) JavaScript engines, there's no `Math.trunc`, so such code will fail.
66
+
67
+
<<<<<<< HEAD
52
68
```offline
53
69
As you're reading the offline version, examples are not runnable. But they usually work :)
54
70
```
55
71
56
72
[Chrome Canary](https://www.google.com/chrome/browser/canary.html) is good for all examples, but other modern browsers are mostly fine too.
57
73
58
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
+
As we're talking about newfunctions, not syntax changes, there's no need to transpile anything here. We just need to declare the missing function.
77
+
78
+
A script that updates/adds new functions is called "polyfill". It "fills in" the gap and adds missing implementations.
79
+
80
+
For this particular case, the polyfill for `Math.trunc` is a script that implements it, like this:
81
+
82
+
```js
83
+
if (!Math.trunc) { // if no such function
84
+
// implement it
85
+
Math.trunc = function(number) {
86
+
// Math.ceil and Math.floor exist even in ancient JavaScript engines
87
+
// they are covered later in the tutorial
88
+
return number < 0 ? Math.ceil(number) : Math.floor(number);
89
+
};
90
+
}
91
+
```
92
+
93
+
JavaScript is a highly dynamic language, scripts may add/modify any functions, even including built-in ones.
94
+
95
+
Two interesting libraries of polyfills are:
96
+
- [core js](https://github.com/zloirock/core-js) that supports a lot, allows to include only needed features.
97
+
- [polyfill.io](http://polyfill.io) service that provides a script with polyfills, depending on the features and user's browser.
98
+
99
+
100
+
## Summary
101
+
102
+
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.
103
+
104
+
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.
105
+
106
+
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.
107
+
108
+
Good resources that show the current state of support for various features:
109
+
- <https://kangax.github.io/compat-table/es6/> - for pure JavaScript.
110
+
- <https://caniuse.com/> - for browser-related functions.
111
+
112
+
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.
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
+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
@@ -209,7 +209,7 @@ arr.push("Pear"); // modify the array by reference
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.
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.
Copy file name to clipboardExpand all lines: 1-js/11-async/05-promise-api/article.md
+16-2Lines changed: 16 additions & 2 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -269,7 +269,7 @@ The first promise here was fastest, so it became the result. After the first set
269
269
270
270
## Promise.any
271
271
272
-
Similar to `Promise.race`, but waits only for the first fulfilled promise and gets its result. If all of the given promises are rejected, then the returned promise is rejected.
272
+
Similar to `Promise.race`, but waits only for the first fulfilled promise and gets its result. If all of the given promises are rejected, then the returned promise is rejected with [`AggregateError`](mdn:js/AggregateError) - a special error object that stores all promise errors in its `errors` property.
273
273
274
274
The syntax is:
275
275
@@ -289,6 +289,20 @@ Promise.any([
289
289
290
290
The first promise here was fastest, but it was rejected, so the second promise became the result. After the first fulfilled promise "wins the race", all further results are ignored.
As you can see, error objects for failed promises are available in the `errors` property of the `AggregateError` object.
292
306
293
307
## Promise.resolve/reject
294
308
@@ -352,7 +366,7 @@ There are 4 static methods of `Promise` class:
352
366
-`status`: `"fulfilled"` or `"rejected"`
353
367
-`value` (if fulfilled) or `reason` (if rejected).
354
368
3.`Promise.race(promises)` -- waits for the first promise to settle, and its result/error becomes the outcome.
355
-
4.`Promise.any(promises)` -- waits for the first promise to fulfill, and its result becomes the outcome. If all of the given promises rejects, it becomes the error of `Promise.any`.
369
+
4.`Promise.any(promises)` -- waits for the first promise to fulfill, and its result becomes the outcome. If all of the given promises are rejected, [`AggregateError`](mdn:js/AggregateError) becomes the error of `Promise.any`.
356
370
5.`Promise.resolve(value)` -- makes a resolved promise with the given value.
357
371
6.`Promise.reject(error)` -- makes a rejected promise with the given error.
Copy file name to clipboardExpand all lines: 1-js/99-js-misc/01-proxy/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
@@ -969,7 +969,7 @@ Initially, `revoke` is separate from `proxy`, so that we can pass `proxy` around
969
969
970
970
We can also bind `revoke` method to proxy by setting `proxy.revoke = revoke`.
971
971
972
-
Another option is to create a `WeakMap` that has `proxy` as the key the corresponding `revoke` as the value, that allows to easily find `revoke` for a proxy:
972
+
Another option is to create a `WeakMap` that has `proxy` as the key and the corresponding `revoke` as the value, that allows to easily find `revoke` for a proxy:
Copy file name to clipboardExpand all lines: 2-ui/1-document/07-modifying-document/10-clock-setinterval/solution.md
+7-3Lines changed: 7 additions & 3 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -39,15 +39,19 @@ The clock-managing functions:
39
39
```js
40
40
let timerId;
41
41
42
-
functionclockStart() { // run the clock
43
-
timerId =setInterval(update, 1000);
42
+
functionclockStart() { // run the clock
43
+
if (!timerId) { // only set a new interval if the clock is not running
44
+
timerId =setInterval(update, 1000);
45
+
}
44
46
update(); // (*)
45
47
}
46
48
47
49
functionclockStop() {
48
50
clearInterval(timerId);
49
-
timerId =null;
51
+
timerId =null;// (**)
50
52
}
51
53
```
52
54
53
55
Please note that the call to `update()` is not only scheduled in `clockStart()`, but immediately run in the line `(*)`. Otherwise the visitor would have to wait till the first execution of `setInterval`. And the clock would be empty till then.
56
+
57
+
Also it is important to set a new interval in `clockStart()` only when the clock is not running. Otherways clicking the start button several times would set multiple concurrent intervals. Even worse - we would only keep the `timerID` of the last interval, losing references to all others. Then we wouldn't be able to stop the clock ever again! Note that we need to clear the `timerID` when the clock is stopped in the line `(**)`, so that it can be started again by running `clockStart()`.
0 commit comments