1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
|
---
title: let
slug: Web/JavaScript/Reference/Statements/let
translation_of: Web/JavaScript/Reference/Statements/let
---
<div>{{jsSidebar("Statements")}}</div>
<p>L'istruzione <strong>let </strong>dichiara una variabile locale nel blocco di codice e, facoltativamente, la inizializza ad un valore.</p>
<div>{{EmbedInteractiveExample("pages/js/statement-let.html")}}</div>
<div class="hidden">Il codice sorgente di questo esempio interattivo è salvato in un repository GitHub. Se tu volessi contribuire al progetto 'interactive examples', puoi clonare <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> e sottomettere una pull request.</div>
<h2 id="Summary" name="Summary">Sintassi</h2>
<pre class="syntaxbox notranslate">let <var>var1</var> [= <var>value1</var>] [, <var>var2</var> [= <var>value2</var>]] [, ..., <var>varN</var> [= <var>valueN</var>]];
</pre>
<h3 id="Parameters" name="Parameters">Parametri</h3>
<dl>
<dt><code><var>var1</var></code>, <code><var>var2</var></code>, …, <code><var>varN</var></code></dt>
<dd>Il nome della variabile o delle variabili da dichiarare. Devono essere identificatori JavaScript validi.</dd>
<dt><code><var>value1</var></code>, <code><var>value2</var></code>, …, <code><var>valueN</var></code> {{optional_inline}}</dt>
<dd>Per ogni variabile definita, è possibile specificare il valore iniziale usando qualunque espressione JavaScript valida.</dd>
</dl>
<h2 id="Description" name="Description">Descrizione</h2>
<p><strong><code>let</code></strong> permette di dichiarare variabili limitandone la visibilità ad un {{jsxref("statements/block", "blocco di codice", "", 1)}}, o ad un'espressione in cui è usata, contrariamente alla parola chiave <a href="/it/docs/JavaScript/Reference/Statements/var" title="JavaScript/Reference/Statements/var"><code>var</code></a>, che invece definisce una variabile globalmente in uno script o localmente in una funzione a prescindere dal blocco di codice. L'altra differenza tra {{jsxref("statements/var", "var")}} e <code>let</code> è che la seconda è inizializzata ad un valore solo quando un parser la evaluta (vedi sotto).</p>
<h2 id="Block_scoping" name="Block_scoping">Esempi</h2>
<h3 id="Regole_di_visibilità">Regole di visibilità</h3>
<p>Le variabili inizializzate da <code>let</code> sono legate al blocco dell'espressione in cui sono dichiarate. Il suo funzionamento è del tutto simile a quello di <code>var</code>, ma le variabili definite da quest'ultima istruzione sono sempre variabili globali a livello di programma o di funzione, hanno quindi una visibilità più ampia.</p>
<pre class="notranslate">function varTest() {
var x = 1;
{
var x = 2; // same variable!
console.log(x); // 2
}
console.log(x); // 2
}
function letTest() {
let x = 1;
{
let x = 2; // different variable
console.log(x); // 2
}
console.log(x); // 1
}</pre>
<p>Dichiarare nuovamente la stessa variabile con <code>let</code> restituisce l'errore <code><a href="/it/docs/JavaScript/Reference/Global_Objects/TypeError" title="TypeError">TypeError</a>.</code></p>
<pre class="brush: js notranslate"><code>
if (x) {
let foo;
let foo; // lancia un errore TypeError.
}</code></pre>
<p>Se usata al livello più alto di programma, <code>let</code>, a differenza di <code>var</code>, non crea una proprietà seuul'oggetto globale. Per esempio:</p>
<pre class="notranslate">var x = 'global';
let y = 'global';
console.log(this.x); // "global"
console.log(this.y); // undefined</pre>
<p>Potresti imbatterti in errori in un blocco <a href="/it/docs/JavaScript/Reference/Statements/switch" title="switch"><code>switch</code></a> perché i casi non vengono separati ma fanno parte tutti dello stesso blocco.</p>
<pre class="brush: js notranslate"><code>
switch (x) {
case 0:
let foo;
break;
case 1:
let foo; // TypeError for redeclaration.
break;
}</code></pre>
<h2 id="Examples" name="Examples"><code>Esempi</code></h2>
<p>Una <em><code>let</code> expression</em> può essere usata per limitare la visibilità della variabile dichiarata alla sola espressione chiamata.</p>
<pre class="brush: js notranslate"><code>
var a = 5;
let(a = 6) alert(a); // 6
alert(a); // 5</code></pre>
<p>Usando <code>let</code> in un blocco di codice ne limitiamo la visibilità al solo blocco racchiuso. Nel codice di esempio nota come le due assegnazioni nel blocco <code>if</code> diano due risultati diversi.</p>
<pre class="brush: js notranslate"><code>
var a = 5;
var b = 10;
if (a === 5) {
let a = 4; // La visibilità è dentro il blocco if
var b = 1; // La visibilità è dentro la funzione
console.log(a); // 4
console.log(b); // 1
}
console.log(a); // 5
console.log(b); // 1</code></pre>
<p>Puoi usare <strong><code>let</code></strong> come iteratore in un ciclo <strong><code>for</code></strong> invece di usare una nuova variabile globale.</p>
<pre class="brush: js notranslate"><code>
for (let i = 0; i<10; i++) {
alert(i); // 1, 2, 3, 4 ... 9
}
alert(i); // i non è definita</code></pre>
<p>Quando lavori con i costruttori puoi usare <code>let</code> per creare in'interfaccia privata senza chiusure.</p>
<pre class="brush: js notranslate"><code>
/*\
|*|
|*| :: Una API pubblica e riutilizzabile per i costruttori ... ::
|*|
\*/
let (
switchScope = function (oOwner, fConstructor) {
return oOwner && oOwner.constructor === fConstructor ? oOwner : this;
}
) {
function buildIndoors (fConstructor) {
const oPrivate = new fConstructor(this);
this.getScope = oPrivate.getScope = switchScope.bind(this, oPrivate);
return oPrivate;
}
}
/*\
|*|
|*| :: Use of the *let* statement in order to create a private interface without closures... ::
|*|
\*/
let (
/* "Secrets" is the constructor of the private interface */
Secrets = function Secrets (oPublic /* (the public interface) */) {
/* setting a private property... */
this.password = Math.floor(Math.random() * 1e16).toString(36);
/* you can also store the public interface into a private property... */
/* this.publicInterface = oPublic; */
alert("I\'m getting a public property from a private constructor...: somePublicProperty: " + oPublic.somePublicProperty);
}
) {
/* "User" is the constructor of the public interface */
function User (sNick) {
/* setting a public property... */
this.somePublicProperty = "Hello World!";
const oPrivate = this.createScope(Secrets); /* (the private interface) */
/* setting a public property... */
this.user = sNick;
alert("I\'m getting a private property from a public constructor...: password: " + oPrivate.password);
}
User.prototype.somePublicMethod = function () {
const oPrivate = this.getScope(Secrets); /* (the private interface) */
alert("I\'m getting a public property from a public method...: user: " + this.user);
alert("I\'m getting a private property from a public method...: password: " + oPrivate.password);
oPrivate.somePrivateMethod();
};
Secrets.prototype.somePrivateMethod = function () {
const oPublic = this.getScope(); /* (the public interface) */
alert("I\'m getting a public property from a private method...: user: " + oPublic.user);
alert("I\'m getting a private property from a private method...: password: " + this.password);
};
/* ...creating a mutual access... */
User.prototype.createScope = buildIndoors;
}
/* out of the *let* statement you have not access to the private interface! */
const johnSmith = new User("John Smith");
johnSmith.somePublicMethod();</code></pre>
<h2 id="Browser_compatibility">Browser compatibility</h2>
<div class="hidden">The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</div>
<p>{{Compat("javascript.statements.let")}}</p>
<h2 id="See_also" name="See_also"></h2>
<h2 id="See_also" name="See_also"><code>See also</code></h2>
<ul>
<li><code><a href="/it/docs/JavaScript/Reference/Statements/var" title="JavaScript/Reference/Statements/var"><code>var</code></a></code></li>
<li><code><a href="/it/docs/JavaScript/Reference/Statements/const" title="JavaScript/Reference/Statements/const"><code>const</code></a></code></li>
<li><code><a href="/it/docs/JavaScript/New_in_JavaScript/1.7#Block_scope_with_let_(Merge_into_let_Statement)" title="JavaScript/New in JavaScript/1.7#Block scope with let (Merge into let Statement)">New in JavaScript 1.7</a></code></li>
</ul>
|