--- title: let slug: Web/JavaScript/Reference/Statements/let translation_of: Web/JavaScript/Reference/Statements/let ---
L'istruzione let dichiara una variabile locale nel blocco di codice e, facoltativamente, la inizializza ad un valore.
let var1 [= value1] [, var2 [= value2]] [, ..., varN [= valueN]];
var1
, var2
, …, varN
value1
, value2
, …, valueN
{{optional_inline}}let
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 var
, 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 let
è che la seconda è inizializzata ad un valore solo quando un parser la evaluta (vedi sotto).
Le variabili inizializzate da let
sono legate al blocco dell'espressione in cui sono dichiarate. Il suo funzionamento è del tutto simile a quello di var
, 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.
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 }
Dichiarare nuovamente la stessa variabile con let
restituisce l'errore TypeError.
if (x) {
let foo;
let foo; // lancia un errore TypeError.
}
Se usata al livello più alto di programma, let
, a differenza di var
, non crea una proprietà seuul'oggetto globale. Per esempio:
var x = 'global'; let y = 'global'; console.log(this.x); // "global" console.log(this.y); // undefined
Potresti imbatterti in errori in un blocco switch
perché i casi non vengono separati ma fanno parte tutti dello stesso blocco.
switch (x) {
case 0:
let foo;
break;
case 1:
let foo; // TypeError for redeclaration.
break;
}
Esempi
Una let
expression può essere usata per limitare la visibilità della variabile dichiarata alla sola espressione chiamata.
var a = 5;
let(a = 6) alert(a); // 6
alert(a); // 5
Usando let
in un blocco di codice ne limitiamo la visibilità al solo blocco racchiuso. Nel codice di esempio nota come le due assegnazioni nel blocco if
diano due risultati diversi.
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
Puoi usare let
come iteratore in un ciclo for
invece di usare una nuova variabile globale.
for (let i = 0; i<10; i++) {
alert(i); // 1, 2, 3, 4 ... 9
}
alert(i); // i non è definita
Quando lavori con i costruttori puoi usare let
per creare in'interfaccia privata senza chiusure.
/*\
|*|
|*| :: 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();
{{Compat("javascript.statements.let")}}
See also