let allows variables to be declared by limiting their scope to the block, statement, or expression where they are being used. This differentiates the let expression from the var keyword, which defines a global or local variable in a function regardless of the scope of the block.
let vs var
When we use let inside a block, we can limit the scope of the variable to that block. Note the difference between a and var, whose scope resides within the function where the variable has been declared.
var a = 5;
var b = 10;
if (a === 5) {
let a = 4; // El alcance es dentro del bloque if
var b = 1; // El alcance es global
console.log(a); // 4
console.log(b); // 1
}
console.log(a); // 5
console.log(b); // 1
letdefines a local variable by limiting its scope to the execution block, expression, or statement it is in. It is a non-standard feature so it can cause problems in different browsers.
vardefines a variable by limiting its scope to the function in which it is defined or to the global scope (if it is not inside a function), regardless of the block of execution in which it is executed.
{
let variable_let = 'valor variable let';
var variable_var = 'valor variable var';
console.log('var dentro de bloque: ' + variable_var);
console.log('let dentro de bloque: ' + variable_let);
}
console.log('var fuera de bloque: ' + variable_var);
console.log('let fuera de bloque: ' + variable_let);
Several, but the most significant have to do with scope:
function cualquiera(){
if (2 == 2){ // por poner algo
var variable1 = 1
let variable2 = 2
}
// aqui variable1 existe
// aqui variable2 no existe
console.log(variable1)
}
The idea (IMHO) is that you use varfor things that are private to the module and letfor things that are local to functions.
let allows variables to be declared by limiting their scope to the block, statement, or expression where they are being used. This differentiates the let expression from the var keyword, which defines a global or local variable in a function regardless of the scope of the block.
let vs var
When we use let inside a block, we can limit the scope of the variable to that block. Note the difference between a and var, whose scope resides within the function where the variable has been declared.
Source: Mozilla Developer
let
defines a local variable by limiting its scope to the execution block, expression, or statement it is in. It is a non-standard feature so it can cause problems in different browsers.var
defines a variable by limiting its scope to the function in which it is defined or to the global scope (if it is not inside a function), regardless of the block of execution in which it is executed.Several, but the most significant have to do with scope:
The idea (IMHO) is that you use
var
for things that are private to the module andlet
for things that are local to functions.