Well, fundamentally speaking, var
and let
are modifiers of the scope scope of the variable, that is, define how far you can reference that variable within the scope in question.
Explanations
Modifier var
As the majority already knows, var
serves to make the local variable accessible only to its function scope, because if you declare a variable with no modifier it ends up having its scope scope as a global variable, or either you can get the reference from within any scope.
Example
z = 0;
function foo(){
var x = 3;
console.log(x); //resultará 3.
console.log(z); //resultará 0.
console.log(y); //aqui a variável y do escopo de bar() não é accesível, por isso resultará undefined.
}
function bar(){
var y = 4;
console.log(y); //resultará 4.
console.log(z); //resultará 0.
console.log(x); //aqui a variável x do escopo de foo() não é accesível, por isso resultará undefined.
}
console.log(z); //resultará 0.
console.log(x); //aqui a variável x do escopo de foo() não é acessível e resultará em undefined.
console.log(y); //aqui a variável y do escopo de bar() não é acessível e resultará em undefined.
As you can see above, the variable z
was not assigned with the var
modifier and ends up being accessible in any execution context, now for the variables assigned with the var
modifier are accessible only to your current execution context.
Modifier let
While let
causes the scope of the variable to declare it abstains from the block of code or expression where it was declared just .
Example
function foo(){
var x = 1;
let y = 3;
if (true){
var x = 2;
let y = 4;
console.log(x); //Irá resultar 2.
console.log(y); //Irá resultar 4.
}
console.log(x); //Irá resultar 2 porque o escopo do 'var' abrangiu toda a função foo().
console.log(y); //Irá resultar 3 porque o escopo do 'let' abrangiu apenas o bloco, diferente da atribuição na expressão if.
}
Note that the assignment of the variable y
to the value 3
outside the if expression only applies to the log outside the if expression, since the assignment of the variable y
to the value 4
inside the if expression, only holds for the log that is inside the if expression. This implies that let
only declares a variable for use in its block / expression, so within the if expression it no longer has the same context.
Conclusion
The difference between var
and let
is only to specify the scope of the variable in question.
Sources / References: