Skip to content

Commit 6d245f5

Browse files
authored
Merge pull request #199 from javascript-tutorial/sync-c56e6a57
Sync with upstream @ c56e6a5
2 parents 118b67d + d3d9a7c commit 6d245f5

File tree

32 files changed

+354
-323
lines changed

32 files changed

+354
-323
lines changed
Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,21 @@
1-
Primeiro, a variável para o nome do nosso planeta.
1+
## A variável para o nosso planeta
22

33
Isso é simples:
44

55
```js
66
let ourPlanetName = "Earth";
77
```
88

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.
1010

11-
Em segundo lugar, o nome do visitante atual:
11+
## O nome do visitante atual
1212

1313
```js
1414
let currentUserName = "John";
1515
```
1616

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.
1818

1919
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.
2020

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).

1-js/03-code-quality/06-polyfills/article.md

Lines changed: 62 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11

2-
# Polyfills
2+
# Polyfills and transpilers
33

44
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).
55

@@ -9,50 +9,84 @@ So it's quite common for an engine to implement only the part of the standard.
99

1010
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).
1111

12-
## Babel
12+
As programmers, we'd like to use most recent features. The more good stuff - the better!
1313

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?
1515

16-
Here Babel comes to the rescue.
16+
There are two tools for that:
1717

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.
1920

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.
2122

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
2324

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.
2526

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`.
2828

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`.
3030

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;
3434

35-
So, we need to setup the transpiler and add the polyfill for old engines to support modern features.
35+
// after running the transpiler
36+
height = (height !== undefined && height !== null) ? height : 100;
37+
```
3638
37-
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.
3840
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.
4042
43+
Speaking of names, [Babel](https://babeljs.io) is one of the most prominent transpilers out there.
4144
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.
4446
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`.
4852
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.
5154
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+
}
5470
```
5571
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.
5792
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.

1-js/05-data-types/04-array/10-maximal-subarray/solution.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ alert( getMaxSubSum([1, 2, 3]) ); // 6
5757
alert( getMaxSubSum([100, -9, 2, -3, 5]) ); // 100
5858
```
5959

60-
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.
6161

6262
For big arrays (1000, 10000 or more items) such algorithms can lead to a serious sluggishness.
6363

1-js/05-data-types/04-array/article.md

Lines changed: 20 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
1-
# Arrays
1+
# Arrays
22

33
Objects allow you to store keyed collections of values. That's fine.
44

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.
66

77
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.
88

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.
1010

1111
## Declaration
1212

@@ -81,10 +81,10 @@ arr[3](); // hello
8181

8282
````smart header="Trailing comma"
8383
An array, just like an object, may end with a comma:
84-
```js
84+
```js
8585
let fruits = [
86-
"Apple",
87-
"Orange",
86+
"Apple",
87+
"Orange",
8888
"Plum"*!*,*/!*
8989
];
9090
```
@@ -95,7 +95,7 @@ The "trailing comma" style makes it easier to insert/remove items, because all l
9595

9696
## Methods pop/push, shift/unshift
9797

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:
9999

100100
- `push` appends an element to the end.
101101
- `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.
106106

107107
In practice we need it very often. For example, a queue of messages that need to be shown on-screen.
108108

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)).
110110

111111
It supports two operations:
112112

@@ -121,7 +121,7 @@ A stack is usually illustrated as a pack of cards: new cards are added to the to
121121

122122
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).
123123

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.
125125

126126
In computer science the data structure that allows this, is called [deque](https://en.wikipedia.org/wiki/Double-ended_queue).
127127

@@ -189,7 +189,7 @@ alert( fruits );
189189

190190
## Internals
191191

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.
193193

194194
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.
195195

@@ -203,13 +203,13 @@ let fruits = ["Banana"]
203203
let arr = fruits; // copy by reference (two variables reference the same array)
204204

205205
alert( arr === fruits ); // true
206-
206+
207207
arr.push("Pear"); // modify the array by reference
208208

209209
alert( fruits ); // Banana, Pear - 2 items now
210210
```
211211

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.
213213

214214
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.
215215

@@ -229,7 +229,7 @@ But the engine will see that we're working with the array as with a regular obje
229229

230230
The ways to misuse an array:
231231

232-
- Add a non-numeric property like `arr.test = 5`.
232+
- Add a non-numeric property like `arr.test = 5`.
233233
- Make holes, like: add `arr[0]` and then `arr[1000]` (and nothing between them).
234234
- Fill the array in the reverse order, like `arr[1000]`, `arr[999]` and so on.
235235

@@ -296,7 +296,7 @@ let fruits = ["Apple", "Orange", "Plum"];
296296

297297
// iterates over array elements
298298
for (let fruit of fruits) {
299-
alert( fruit );
299+
alert( fruit );
300300
}
301301
```
302302

@@ -320,7 +320,7 @@ But that's actually a bad idea. There are potential problems with it:
320320

321321
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.
322322

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.
324324

325325
Generally, we shouldn't use `for..in` for arrays.
326326

@@ -338,7 +338,7 @@ fruits[123] = "Apple";
338338
alert( fruits.length ); // 124
339339
```
340340

341-
Note that we usually don't use arrays like that.
341+
Note that we usually don't use arrays like that.
342342

343343
Another interesting thing about the `length` property is that it's writable.
344344

@@ -385,7 +385,7 @@ To evade such surprises, we usually use square brackets, unless we really know w
385385

386386
## Multidimensional arrays
387387

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:
389389

390390
```js run
391391
let matrix = [
@@ -394,7 +394,7 @@ let matrix = [
394394
[7, 8, 9]
395395
];
396396

397-
alert( matrix[1][1] ); // the central element
397+
alert( matrix[1][1] ); // 5, the central element
398398
```
399399

400400
## toString
@@ -492,15 +492,15 @@ Array is a special kind of object, suited to storing and managing ordered data i
492492

493493
The call to `new Array(number)` creates an array with the given length, but without elements.
494494

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.
496496
- If we shorten `length` manually, the array is truncated.
497497

498498
We can use an array as a deque with the following operations:
499499

500500
- `push(...items)` adds `items` to the end.
501501
- `pop()` removes the element from the end and returns it.
502502
- `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.
504504

505505
To loop over the elements of the array:
506506
- `for (let i=0; i<arr.length; i++)` -- works fastest, old-browser-compatible.

1-js/05-data-types/08-weakmap-weakset/article.md

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,7 @@ alert(cache.size); // 1 (Ouch! The object is still in cache, taking memory!)
207207

208208
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.
209209

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.
211211

212212
```js run
213213
// 📁 cache.js
@@ -284,7 +284,8 @@ The most notable limitation of `WeakMap` and `WeakSet` is the absence of iterati
284284

285285
`WeakSet` is `Set`-like collection that stores only objects and removes them once they become inaccessible by other means.
286286

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`...
289290

290291
`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.

1-js/06-advanced-functions/06-function-object/5-sum-many-brackets/solution.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
Now the code:
77

8-
```js run
8+
```js demo run
99
function sum(a) {
1010

1111
let currentSum = a;

0 commit comments

Comments
 (0)