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
+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
@@ -6,7 +6,7 @@ That's simple:
6
6
let ourPlanetName ="Earth";
7
7
```
8
8
9
-
Note, we could use a shorter name `planet`, but it might be not obvious what planet it refers to. It's nice to be more verbose. At least until the variable isNotTooLong.
9
+
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,46 +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
-
A script that updates/adds new functions is called "polyfill". It "fills in" the gap and adds 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
-
-[core js](https://github.com/zloirock/core-js) that supports a lot, allows to include only needed features.
33
-
-[polyfill.io](http://polyfill.io) service that provides a script with polyfills, depending on the features and user's browser.
31
+
```js
32
+
// before running the transpiler
33
+
height = height ??100;
34
34
35
-
So, if we're going to use modern language features, a transpiler and a polyfill are necessary.
Now the rewritten code is suitable for older JavaScript engines.
38
40
41
+
Usually, a developer runs the transpiler on their own computer, and then deploys the transpiled code to the server.
39
42
40
-
````online
41
-
Most examples are runnable at-place, like this:
43
+
Speaking of names, [Babel](https://babeljs.io) is one of the most prominent transpilers out there.
42
44
43
-
```js run
44
-
alert('Press the "Play" button in the upper-right corner to run');
45
-
```
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.
46
+
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`.
46
52
47
-
Examples that use modern JS will work only if your browser supports it.
48
-
````
53
+
In some (very outdated) JavaScript engines, there's no `Math.trunc`, so such code will fail.
49
54
50
-
```offline
51
-
As you're reading the offline version, in PDF examples are not runnable. In EPUB some of them can run.
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
+
}
52
70
```
53
71
54
-
Google Chrome is usually the most up-to-date with language features, good to run bleeding-edge demos without any transpilers, but other modern browsers also work fine.
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.
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
@@ -219,7 +219,7 @@ The first promise here was fastest, so it became the result. After the first set
219
219
220
220
## Promise.any
221
221
222
-
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.
222
+
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.
223
223
224
224
The syntax is:
225
225
@@ -239,6 +239,20 @@ Promise.any([
239
239
240
240
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.
241
241
242
+
Here's an example when all promises fail:
243
+
244
+
```js run
245
+
Promise.any([
246
+
new Promise((resolve, reject) => setTimeout(() => reject(new Error("Ouch!")), 1000)),
247
+
new Promise((resolve, reject) => setTimeout(() => reject(new Error("Error!")), 2000))
As you can see, error objects for failed promises are available in the `errors` property of the `AggregateError` object.
242
256
243
257
## Promise.resolve/reject
244
258
@@ -302,7 +316,7 @@ There are 5 static methods of `Promise` class:
302
316
- `status`: `"fulfilled"` or `"rejected"`
303
317
- `value` (if fulfilled) or `reason` (if rejected).
304
318
3. `Promise.race(promises)` -- waits for the first promise to settle, and its result/error becomes the outcome.
305
-
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`.
319
+
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`.
306
320
5. `Promise.resolve(value)` -- makes a resolved promise with the given value.
307
321
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