Skip to content

Commit 042c98e

Browse files
committed
2 parents 42d55f6 + 42ee148 commit 042c98e

File tree

89 files changed

+682
-572
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

89 files changed

+682
-572
lines changed

1-js/01-getting-started/1-intro/article.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,7 @@ Esempi di alcuni linguaggi:
112112
- [Flow](http://flow.org/) anche'esso aggiunge la tipizzazione dei dati, ma in un modo differente. Sviluppato da Facebook.
113113
- [Dart](https://www.dartlang.org/) è un linguaggio autonomo che possiede il suo motore che esegue in ambienti esterni al browser (come mobile apps). E' stato introdotto da Google come alternativa a JavaScript, ma attualmente, i browser richiedono la conversione in JavaScript, proprio come i precedenti.
114114
- [Brython](https://brython.info/) è un traduttore, che codice scritto in Python in codice JavaScript, consente quindi di scrivere applicazioni in Python senza utilizzare JavaScript.
115+
- [Kotlin](https://kotlinlang.org/docs/reference/js-overview.html) è un moderno, conciso e sicuro linguaggio di programmazione mirato ai browsers o a Node.
115116

116117
Ce ne sono molti altri. Ovviamente se utilizziamo uno di questi linguaggi, dovremmo almeno conoscere JavaScript, per comprendere cosa stiamo facendo.
117118

1-js/02-first-steps/04-variables/2-declare-variables/solution.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ Questo è semplice:
66
let ourPlanetName = "Earth";
77
```
88

9-
Nota che avremmo anche potuto usare un nome più corto, come `planet`, ma potrebbe non essere ovvio a cosa si rifrisce. E' una buona cosa essere un più descrittivi. Almeno finche le variabili nonDiventanoTroppoLunghe.
9+
Nota che avremmo anche potuto usare un nome più corto, come `planet`, ma potrebbe non essere ovvio a cosa si riferisce. E' una buona pratica essere un po' più descrittivi. Almeno finché le variabili nonDiventanoTroppoLunghe.
1010

1111
# Il nome del visitatore attuale
1212

Lines changed: 61 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,55 +1,89 @@
11

2-
# Polyfills
2+
# Polyfills and transpilers
33

4-
Il linguaggio JavaScript si evolte costantemente. Nuove proposte per il linguaggio arrivano regolarmente, vengono analizzatte, e successivamente se ritenute valide vengono aggiunte alla lista <https://tc39.github.io/ecma262/> fino a diventare delle [specifiche](http://www.ecma-international.org/publications/standards/Ecma-262.htm).
4+
Il linguaggio JavaScript si evolve costantemente. Nuove proposte per il linguaggio arrivano regolarmente, vengono analizzate, e successivamente se ritenute valide vengono aggiunte alla lista <https://tc39.github.io/ecma262/> fino a diventare delle [specifiche](http://www.ecma-international.org/publications/standards/Ecma-262.htm).
55

66
I team che stanno dietro il motore di JavaScript hanno le loro personali idee riguardo cosa implementare. Potrebbero quindi decidere di implementare delle proposte recenti e posticipare quelle più vecchie a causa di difficoltà nell'implementazione.
77

88
Quindi per un motore di script è naturale implementare solo le cose che si trovano nello standard.
99

1010
Se si vuole rimanere aggiornati riguardo lo stato di supporto delle caratteristiche si può controllare la pagina <https://kangax.github.io/compat-table/es6/> (è molt grande, dovremmo studiare ancora molto).
1111

12-
## Babel
12+
Come programmatori, amiamo utilizzare le più recenti caratteristiche del linguaggio, ma come si può fare per farle funzionare sui vecchi motori Javascript che non le comprendono ed interpretano?
1313

14-
Quando utilizziamo caratteristiche moderne del linguaggio, alcuni motori potrebbero non supportarle. Infatti, non tutte le caratteristiche sono implementate ovunque.
14+
Esistono due strumenti per questo:
1515

16-
Qui Babel ci viene in soccorso.
16+
1. Transpilers.
17+
2. Polyfills.
1718

18-
[Babel](https://babeljs.io) è un [transpiler](https://en.wikipedia.org/wiki/Source-to-source_compiler). Riscrive il codice da JavaScript moderno ad uno standard precedente.
19+
In questo capitolo cercheremo di capire il loro funzionamento ed il loro ruolo nello sviluppo web.
1920

20-
Babel è composto da due parti:
21+
## Transpilers
2122

22-
1. Primo, il programma che esegue la traduzione, che riscrive quindi il codice. Lo sviluppatore lo esegue sul computer personale. Questo si occuperà di tradurre il codice nei vecchi standard. Verrà poi fornito al sito per gli utenti. Esistono dei progetti di sistemi come [webpack](http://webpack.github.io/) che si occupano di eseguire la traduzione ad ogni cambiamente, evitando perdite di tempo al programmatore.
23+
Un [transpiler](https://en.wikipedia.org/wiki/Source-to-source_compiler) è un particolare software capace di analizzare il codice moderno e di riscriverlo utilizzando sintassi e costrutti meno recenti, facendo in modo che alla fine funzioni nello stesso modo.
2324

24-
2. Secondo, il polyfill.
25+
Es. JavaScript prima del 2020 non aveva "l'operatore di coalescenza nullo" `??`. Quindi, se un visitatore utilizza un vecchio browser, questo non potrebbe comprendere `height = height ?? 100`.
2526

26-
Il transpiler riscrive il codice, quindi la sintassi utilizzata è riconosciuta. Ma per le nuove funzionalità abbiamo bisogno di scrivere uno speciale script che le implementi. JavaScript è un linguaggio altamente dinamico, gli script potrebbero non solo aggiungere nuove funzionalità, ma modificare anche quelle integrate, queste devono quindi essere conformi allo standard.
27+
Un transpiler analizzerebbe il codice e riscriverebbe `height ?? 100` in `(height !== undefined && height !== null) ? height : 100`.
2728

28-
Esiste un termine "polyfill" per gli script che "riempiono" il vuoto aggiungendo funzionalità mancanti.
29+
```js
30+
// prima dell'analisi del transpiler
31+
height = height ?? 100;
2932

30-
Due polyfill importanti sono:
31-
- [core js](https://github.com/zloirock/core-js) ha molto supporto, consente di includere solamente le caratteristiche necessarie.
32-
- [polyfill.io](http://polyfill.io) servizio che consente di caricare costrutti polyfills, in base alle nostre necessità.
33+
// dopo l'analisi del transpiler
34+
height = (height !== undefined && height !== null) ? height : 100;
35+
```
3336
34-
Quindi è necessario settare il transplier e aggiungere polyfill per i vecchi motori di JavaScript, per far si che supportino le caratteristiche moderne.
37+
Ora il codice riscritto è adatto anche ai vecchi motori JavaScript
3538
36-
Se ci spostiamo nella direzione dei moderni motori e non utilizziamo altre caratteristiche se non quelle supportate ovunque, allora non abbiamo bisogno di Babel.
39+
In genere lo sviluppatore fa girare il transpiler in locale sul proprio computer, quindi distribuisce sul server il codice riscritto.
3740
38-
## Esempi nel tutorial
41+
Facendo qualche nome, [Babel](https://babeljs.io) è uno dei più diffusi transpilers del momento.
3942
43+
I moderni 'bundler' utilizzati per 'assemblare' progetti, come [webpack](http://webpack.github.io/), possono eseguire il transpiler automaticamente ad ogni modifica del codice, è quindi molto facile integrarlo nei processi di sviluppo.
4044
41-
````online
42-
Molti esempi sono eseguibili sul posto, come questi:
45+
## Polyfills
4346
44-
```js run
45-
alert('Press the "Play" button in the upper-right corner to run');
46-
```
47+
Nuove caratteristiche di un linguaggio possono riguardare, oltre alla sintassi, operatori e costrutti, anche funzioni integrate.
48+
49+
Ad esempio, `Math.trunc(n)` è una funziona che "taglia" la parte decimale di un numero, es. `Math.trunc(1.23) = 1`.
50+
51+
In alcuni (vecchissimi) motori JavaScript, non esiste `Math.trunc`, quindi il codice non funzionerebbe.
4752
48-
Gli esempio che utilizzano il moderno JS funzioneranno solo se il vostr browser li supporta.
49-
````
53+
Poiché stiamo parlando di nuove funzioni, non di modifiche alla sintassi, in questo caso non ci serve un transpiler. Dobbiamo solo dichiarare la funzione mancante.
5054
51-
```offline
52-
Se satate leggendo la versione offline, gli esempi non sono eseguibili. In EPUB alcuni riescono ad eseguire.
55+
Uno script che aggiorna/aggiunge nuove funzioni è chiamato "polyfill". Questo colma il gap ed aggiunge le implementazioni mancanti.
56+
57+
In questo particolare caso, il polyfill per `Math.trunc` è uno script che implementa la funzione in questo modo :
58+
59+
```js
60+
if (!Math.trunc) { // se la funzione non esiste
61+
// implementala
62+
Math.trunc = function(number) {
63+
// Math.ceil e Math.floor sono presenti anche in vecchi motori JavaScript
64+
// verranno trattati più avanti in questo tutorial
65+
return number < 0 ? Math.ceil(number) : Math.floor(number);
66+
};
67+
}
5368
```
5469
55-
Google Chrome solitamente è quello più aggiornato con le caratteristiche del linguaggio, è ottimo per fare tutti gli esperimenti senza transpilers, ma anche gli altri browser moderni dovrebbero andare bene.
70+
JavaScript è un linguaggio altamente dinamico, gli script possono aggiungere/modificare qualsiasi funzione, anche quelle integrate.
71+
72+
Due interessanti librerie polyfills sono:
73+
- [core js](https://github.com/zloirock/core-js) ha molte funzioni e consente di includere solo le funzionalità necessarie.
74+
- [polyfill.io](http://polyfill.io) servizio che fornisce uno script con polyfill, a seconda delle funzionalità e del browser dell'utente.
75+
76+
77+
## Riepilogo
78+
79+
In questo capitolo vorremmo motivarvi a studiare le funzionalità più moderne ed all'avanguardia" del linguaggio, anche se non sono ancora ben supportate dai motori JavaScript.
80+
81+
Basta non dimenticare di usare transpiler (se si utilizza la sintassi o gli operatori moderni) e i polyfill (per aggiungere funzioni che potrebbero mancare). Questi si assicureranno che il codice funzioni.
82+
83+
Ad esempio, in seguito, quando avrai familiarità con JavaScript, potrai configurare un sistema di compilazione del codice basato su [webpack](http://webpack.github.io/) con [babel-loader](https://github.com/babel/babel-loader) plugin.
84+
85+
Buone risorse che mostrano lo stato attuale del supporto per varie funzionalità:
86+
- <https://kangax.github.io/compat-table/es6/> - per puro JavaScript.
87+
- <https://caniuse.com/> - per le funzioni integrate dei browsers.
88+
89+
P.S. Google Chrome è solitamente il browser più aggiornato con le funzionalità del linguaggio, provalo se una demo tutorial fallisce. Tuttavia, la maggior parte delle demo dei tutorial funziona con qualsiasi browser moderno.

1-js/04-object-basics/02-object-copy/article.md

Lines changed: 23 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
# Object references and copying
22

3-
One of the fundamental differences of objects versus primitives is that objects are stored and copied "by reference", as opposed to primitive values: strings, numbers, booleans, etc -- that are always copied "as a whole value".
3+
One of the fundamental differences of objects versus primitives is that objects are stored and copied "by reference", whereas primitive values: strings, numbers, booleans, etc -- are always copied "as a whole value".
44

5-
That's easy to understand if we look a bit "under a cover" of what happens when we copy a value.
5+
That's easy to understand if we look a bit under the hood of what happens when we copy a value.
66

77
Let's start with a primitive, such as a string.
88

@@ -13,17 +13,17 @@ let message = "Hello!";
1313
let phrase = message;
1414
```
1515

16-
As a result we have two independent variables, each one is storing the string `"Hello!"`.
16+
As a result we have two independent variables, each one storing the string `"Hello!"`.
1717

1818
![](variable-copy-value.svg)
1919

2020
Quite an obvious result, right?
2121

2222
Objects are not like that.
2323

24-
**A variable assigned to an object stores not the object itself, but its "address in memory", in other words "a reference" to it.**
24+
**A variable assigned to an object stores not the object itself, but its "address in memory" -- in other words "a reference" to it.**
2525

26-
Let's look at an example of such variable:
26+
Let's look at an example of such a variable:
2727

2828
```js
2929
let user = {
@@ -37,13 +37,13 @@ And here's how it's actually stored in memory:
3737

3838
The object is stored somewhere in memory (at the right of the picture), while the `user` variable (at the left) has a "reference" to it.
3939

40-
We may think of an object variable, such as `user`, as of a sheet of paper with the address.
40+
We may think of an object variable, such as `user`, as like a sheet of paper with the address of the object on it.
4141

42-
When we perform actions with the object, e.g. take a property `user.name`, JavaScript engine looks into that address and performs the operation on the actual object.
42+
When we perform actions with the object, e.g. take a property `user.name`, the JavaScript engine looks at what's at that address and performs the operation on the actual object.
4343

4444
Now here's why it's important.
4545

46-
**When an object variable is copied -- the reference is copied, the object is not duplicated.**
46+
**When an object variable is copied, the reference is copied, but the object itself is not duplicated.**
4747

4848
For instance:
4949

@@ -53,13 +53,13 @@ let user = { name: "John" };
5353
let admin = user; // copy the reference
5454
```
5555

56-
Now we have two variables, each one with the reference to the same object:
56+
Now we have two variables, each storing a reference to the same object:
5757

5858
![](variable-copy-reference.svg)
5959

60-
As you can see, there's still one object, now with two variables that reference it.
60+
As you can see, there's still one object, but now with two variables that reference it.
6161

62-
We can use any variable to access the object and modify its contents:
62+
We can use either variable to access the object and modify its contents:
6363

6464
```js run
6565
let user = { name: 'John' };
@@ -73,7 +73,7 @@ admin.name = 'Pete'; // changed by the "admin" reference
7373
alert(*!*user.name*/!*); // 'Pete', changes are seen from the "user" reference
7474
```
7575
76-
It's just as if we had a cabinet with two keys and used one of them (`admin`) to get into it. Then, if we later use another key (`user`) we can see changes.
76+
It's as if we had a cabinet with two keys and used one of them (`admin`) to get into it and make changes. Then, if we later use another key (`user`), we are still opening the same cabinet and can access the changed contents.
7777
7878
## Comparison by reference
7979
@@ -98,15 +98,15 @@ let b = {}; // two independent objects
9898
alert( a == b ); // false
9999
```
100100
101-
For comparisons like `obj1 > obj2` or for a comparison against a primitive `obj == 5`, objects are converted to primitives. We'll study how object conversions work very soon, but to tell the truth, such comparisons are needed very rarely, usually they appear as a result of a programming mistake.
101+
For comparisons like `obj1 > obj2` or for a comparison against a primitive `obj == 5`, objects are converted to primitives. We'll study how object conversions work very soon, but to tell the truth, such comparisons are needed very rarely -- usually they appear as a result of a programming mistake.
102102
103103
## Cloning and merging, Object.assign
104104
105105
So, copying an object variable creates one more reference to the same object.
106106
107107
But what if we need to duplicate an object? Create an independent copy, a clone?
108108
109-
That's also doable, but a little bit more difficult, because there's no built-in method for that in JavaScript. Actually, that's rarely needed. Copying by reference is good most of the time.
109+
That's also doable, but a little bit more difficult, because there's no built-in method for that in JavaScript. But there is rarely a need -- copying by reference is good most of the time.
110110
111111
But if we really want that, then we need to create a new object and replicate the structure of the existing one by iterating over its properties and copying them on the primitive level.
112112
@@ -225,12 +225,12 @@ user.sizes.width++; // change a property from one place
225225
alert(clone.sizes.width); // 51, see the result from the other one
226226
```
227227
228-
To fix that, we should use the cloning loop that examines each value of `user[key]` and, if it's an object, then replicate its structure as well. That is called a "deep cloning".
228+
To fix that, we should use a cloning loop that examines each value of `user[key]` and, if it's an object, then replicate its structure as well. That is called a "deep cloning".
229229
230-
We can use recursion to implement it. Or, not to reinvent the wheel, take an existing implementation, for instance [_.cloneDeep(obj)](https://lodash.com/docs#cloneDeep) from the JavaScript library [lodash](https://lodash.com).
230+
We can use recursion to implement it. Or, to not reinvent the wheel, take an existing implementation, for instance [_.cloneDeep(obj)](https://lodash.com/docs#cloneDeep) from the JavaScript library [lodash](https://lodash.com).
231231
232-
```smart header="Const objects can be modified"
233-
An important "side effect" of storing objects as references is that an object declared as `const` *can* be modified.
232+
````smart header="Const objects can be modified"
233+
An important side effect of storing objects as references is that an object declared as `const` *can* be modified.
234234

235235
For instance:
236236

@@ -246,16 +246,16 @@ user.name = "Pete"; // (*)
246246
alert(user.name); // Pete
247247
```
248248

249-
It might seem that the line `(*)` would cause an error, but no. The value of `user` is constant, it must always reference the same object. But properties of that object are free to change.
249+
It might seem that the line `(*)` would cause an error, but it does not. The value of `user` is constant, it must always reference the same object, but properties of that object are free to change.
250250

251-
In other words, the `const user` gives an error only if we try to set `user=...` as a whole, and that's all.
251+
In other words, the `const user` gives an error only if we try to set `user=...` as a whole.
252252

253-
That said, if we really need to make constant object properties, it's also possible, but using totally different methods, we'll mention that in the chapter <info:property-descriptors>.
254-
```
253+
That said, if we really need to make constant object properties, it's also possible, but using totally different methods. We'll mention that in the chapter <info:property-descriptors>.
254+
````
255255

256256
## Summary
257257

258-
Objects are assigned and copied by reference. In other words, a variable stores not the "object value", but a "reference" (address in memory) for the value. So copying such a variable or passing it as a function argument copies that reference, not the object.
258+
Objects are assigned and copied by reference. In other words, a variable stores not the "object value", but a "reference" (address in memory) for the value. So copying such a variable or passing it as a function argument copies that reference, not the object itself.
259259

260260
All operations via copied references (like adding/removing properties) are performed on the same single object.
261261

1-js/04-object-basics/07-optional-chaining/article.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ The optional chaining `?.` is a safe way to access nested object properties, eve
99

1010
If you've just started to read the tutorial and learn JavaScript, maybe the problem hasn't touched you yet, but it's quite common.
1111

12-
As an example, let's say we have `user` objects that hold the information about our users.
12+
As an example, let's say we have `user` objects that hold the information about our users.
1313

1414
Most of our users have addresses in `user.address` property, with the street `user.address.street`, but some did not provide them.
1515

@@ -21,7 +21,7 @@ let user = {}; // a user without "address" property
2121
alert(user.address.street); // Error!
2222
```
2323

24-
That's the expected result. JavaScript works like this. As `user.address` is `undefined`, an attempt to get `user.address.street` fails with an error.
24+
That's the expected result. JavaScript works like this. As `user.address` is `undefined`, an attempt to get `user.address.street` fails with an error.
2525

2626
In many practical cases we'd prefer to get `undefined` instead of an error here (meaning "no street").
2727

@@ -56,7 +56,7 @@ let user = {}; // user has no address
5656
alert(user.address ? user.address.street ? user.address.street.name : null : null);
5757
```
5858

59-
That's just awful, one may even have problems understanding such code.
59+
That's just awful, one may even have problems understanding such code.
6060

6161
Don't even care to, as there's a better way to write it, using the `&&` operator:
6262

@@ -219,4 +219,4 @@ As we can see, all of them are straightforward and simple to use. The `?.` check
219219
220220
A chain of `?.` allows to safely access nested properties.
221221
222-
Still, we should apply `?.` carefully, only where it's acceptable that the left part doesn't to exist. So that it won't hide programming errors from us, if they occur.
222+
Still, we should apply `?.` carefully, only where it's acceptable that the left part doesn't exist. So that it won't hide programming errors from us, if they occur.

0 commit comments

Comments
 (0)