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/01-getting-started/1-intro/article.md
+1Lines changed: 1 addition & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -112,6 +112,7 @@ Esempi di alcuni linguaggi:
112
112
-[Flow](http://flow.org/) anche'esso aggiunge la tipizzazione dei dati, ma in un modo differente. Sviluppato da Facebook.
113
113
-[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.
114
114
-[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.
115
116
116
117
Ce ne sono molti altri. Ovviamente se utilizziamo uno di questi linguaggi, dovremmo almeno conoscere JavaScript, per comprendere cosa stiamo facendo.
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 @@ Questo è semplice:
6
6
let ourPlanetName ="Earth";
7
7
```
8
8
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 pò 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.
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).
5
5
6
6
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.
7
7
8
8
Quindi per un motore di script è naturale implementare solo le cose che si trovano nello standard.
9
9
10
10
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).
11
11
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?
13
13
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:
15
15
16
-
Qui Babel ci viene in soccorso.
16
+
1. Transpilers.
17
+
2. Polyfills.
17
18
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.
19
20
20
-
Babel è composto da due parti:
21
+
## Transpilers
21
22
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.
23
24
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`.
25
26
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`.
27
28
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;
29
32
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à.
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
35
38
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.
37
40
38
-
## Esempi nel tutorial
41
+
Facendo qualche nome, [Babel](https://babeljs.io) è uno dei più diffusi transpilers del momento.
39
42
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.
40
44
41
-
````online
42
-
Molti esempi sono eseguibili sul posto, come questi:
45
+
## Polyfills
43
46
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 "tronca" 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.
47
52
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.
50
54
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
+
}
53
68
```
54
69
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.
Copy file name to clipboardExpand all lines: 1-js/04-object-basics/02-object-copy/article.md
+23-23Lines changed: 23 additions & 23 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,8 +1,8 @@
1
1
# Object references and copying
2
2
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".
4
4
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.
6
6
7
7
Let's start with a primitive, such as a string.
8
8
@@ -13,17 +13,17 @@ let message = "Hello!";
13
13
let phrase = message;
14
14
```
15
15
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!"`.
17
17
18
18

19
19
20
20
Quite an obvious result, right?
21
21
22
22
Objects are not like that.
23
23
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.**
25
25
26
-
Let's look at an example of such variable:
26
+
Let's look at an example of such a variable:
27
27
28
28
```js
29
29
let user = {
@@ -37,13 +37,13 @@ And here's how it's actually stored in memory:
37
37
38
38
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.
39
39
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.
41
41
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.
43
43
44
44
Now here's why it's important.
45
45
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.**
47
47
48
48
For instance:
49
49
@@ -53,13 +53,13 @@ let user = { name: "John" };
53
53
let admin = user; // copy the reference
54
54
```
55
55
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:
57
57
58
58

59
59
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.
61
61
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:
63
63
64
64
```js run
65
65
let user = { name:'John' };
@@ -73,7 +73,7 @@ admin.name = 'Pete'; // changed by the "admin" reference
73
73
alert(*!*user.name*/!*); //'Pete', changes are seen from the "user" reference
74
74
```
75
75
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.
77
77
78
78
## Comparison by reference
79
79
@@ -98,15 +98,15 @@ let b = {}; // two independent objects
98
98
alert( a == b ); // false
99
99
```
100
100
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.
102
102
103
103
## Cloning and merging, Object.assign
104
104
105
105
So, copying an object variable creates one more reference to the same object.
106
106
107
107
But what if we need to duplicate an object? Create an independent copy, a clone?
108
108
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.
110
110
111
111
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.
112
112
@@ -225,12 +225,12 @@ user.sizes.width++; // change a property from one place
225
225
alert(clone.sizes.width); // 51, see the result from the other one
226
226
```
227
227
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".
229
229
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).
231
231
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* bemodified.
234
234
235
235
For instance:
236
236
@@ -246,16 +246,16 @@ user.name = "Pete"; // (*)
246
246
alert(user.name); // Pete
247
247
```
248
248
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.
250
250
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.
252
252
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
+
````
255
255
256
256
## Summary
257
257
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.
259
259
260
260
All operations via copied references (likeadding/removingproperties) are performed on the same single object.
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.
60
60
61
61
Don't even care to, as there's a better way to write it, using the `&&` operator:
62
62
@@ -219,4 +219,4 @@ As we can see, all of them are straightforward and simple to use. The `?.` check
219
219
220
220
A chain of `?.` allows to safely access nested properties.
221
221
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