What is the difference between variable declaration using LeT and var?
Since the word let
was introduced in ECMAScript I have only heard about it, until then I have not seen any practical example and to be honest I do not know very well what a variable let
is and how it behaves. The only thing I understood, and quite superficially, is that it serves to declare a local variable, something related to scope.
What are variables let
? What are they for? When to use them instead of var
?
6 answers
There is a difference in scope.
You should know that any variable "declared" Without let
, var
or const
has global scope, it goes for the entire script.
You may know that you should always use var
to make the scope local, i.e. it only applies within the function where it was declared (it can be global if it is not within a function).
But this was not enough, need to have a block scope. let
has been created, and is available on newer versions of the language just to provide this more limited scope.
Examples:
function exemplo() {
console.log(x);
for (var x = 0; x < 5; x++) {
console.log(x);
};
console.log(x);
};
function exemplo2() {
//console.log(x); //daria erro
for (let x = 0; x < 5; x++ ) {
console.log(x);
};
//console.log(x); //daria erro
}
exemplo();
console.log(" ");
exemplo2();
I put on GitHub for future reference .
const
it can be used in newer versions of the language and is equivalent to let
only it is a constant.
Since it is not any browser that supports these newer commands, they should be avoid.
When given to use in general, let
is preferable, the narrower scope is always preferable. Although if you keep your functions very small as you command such "good practices" it will not make so much difference to use one or the other. And in fact sometimes var
is a hand in the wheel when it needs the "Live" value after the end of a scope (not that it can't handle let
either).
Has yet another reason for let
to have been created is to solve a question of creating their own references in closures , they couldn't change the semantics of the language into something that already existed, they created something new, so the new semantics would be opt-in. Let's look at this example:
var funcs = [];
for (var i = 0; i < 3; i++) {
funcs[i] = () => console.log("Valor: " + i);
}
for (var j = 0; j < 3; j++) {
funcs[j]();
}
Sounds weird, right? The var
leaves the variable alive throughout the function where it is declared (in this case it is even global, but gives anyway), so capturing a closure takes a reference to that variable which is considered universal for function. Now let's see with the let
which makes the scope as small as possible, that is, the variable only exists in the Block for
:
var funcs = [];
for (let i = 0; i < 3; i++) {
funcs[i] = () => console.log("Valor: " + i);
}
for (let j = 0; j < 3; j++) {
funcs[j]();
}
So as long as you use Edge, FireFox 44 forward, Chrome since 49 (41 in strict mode, since 4 Connect manually), Safari 11 and others based on them, prefer let
. IE 11 accepts let
, but does not treat closure correctly. That is where it does not work the person is already used to a lot of things going wrong.
Just remember that if you use let
you should use some transpilator that generates code more suitable for old versions, or be absolutely sure that your page will never be accessed by old browsers. Ensuring this, in general, you should always prefer let
. The var
gets to run on Old browsers that you won't run a Babel or something.
let
andvar
have many similarities but some important differences.
Differences:
- let
does not export to global
A globally scoped variable declared with let
is not exported as global.
Example ( link):
var x = 'foo';
let y = 'bar';
console.log(window.x, window.y); // foo undefined
- let
creates a block scope even within if
statements.
Unlike var
which when used overrides / re-initiates the variable and makes it available within from the scope of the function it is in, let
is more refined / detailed and allows differences in block scope. This is valid for blocks if
, for
, while
for example.
Example ( link):
var x = 'foo1';
let y = 'bar1';
if (true == true) {
var x = 'foo2';
let y = 'bar2';
console.log(x, y); // foo2 bar2
}
console.log(x, y); // foo2 bar1
- re-declaring a variable with let
in the same scope gives error
If we re-declare a variable twice in the same scope var give error. This prevents difficult-to-detect errors.
var x = 'foo1';
let y = 'bar1';
var x = 'foo2';
let y = 'bar2'; // Uncaught SyntaxError: Identifier 'y' has already been declared
- let
can only be used in the following line
Com var
it is possible to declare a variable and use it within the scope. Even if the code has not yet read the line that assigns the value to the variable it is already started and how much gives undefined
. With let
this would give error.
That is, this works:
console.log(x); // undefined
var x = 'foo';
But this gives error:
console.log(x); // Uncaught ReferenceError: x is not defined
let x = 'foo';
As described in MDN :
Let allows you to declare variables by limiting their scope in the Block, statement, or in an expression in which it is used. This is the inverse of keyword var, which defines a variable globally or in the entire scope of a function, regardless of the block scope.
A very simple example using the loop for
:
for (let i = 0; i < 10; i++) {
alert(i); // 1, 2, 3, 4 ... 9
}
alert(i); // i não está definida
for (var i = 0; i < 10; i++) {
alert(i); // 1, 2, 3, 4 ... 9
}
alert(i); // 10
Well, fundamentally speaking, var
and let
are modifiers of the scope of the variable, that is, they define how far it is possible to reference such a variable within the scope in question.
Explanations
Modifier var
As most people already know, var
serves to make the local variable accessible only to its function scope, because if you declare a variable without any modifier it ends up having its scope as a variable global, that is, you will be able to get the reference from it 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 understand above, the variable z
was not assigned with the modifier var
and turns out to be accessible in any execution context, now for variables assigned with the modifier var
they become accessible only to their current execution context.
Modifier let
Already let
causes the scope of the variable declare to abstain from the block of code or expression where it was declared only .
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.
}
Notice that the assignment of the variable y
to the value 3
outside the If expression only applies to the log that is outside the If expression, while the assignment of the variable y
to the value 4
inside the If expression only applies to the log that is inside the If expression. This means that let
only declares a variable for use in its block/expression, so within the expression if he no longer had the same context.
Conclusion
The difference between var
and let
is only to specify the scope of the variable in question.
Sources / References:
Complementing friends ' answer, it's always good you use LET instead of VAR, to avoid so-called hoisting, what is it ?
In JavaScript, functions and variables are hoisted (or "taken to the top"). Hoisting is a JavaScript behavior of moving statements to the top of a scope (the global scope or the function it is in).
This means that you are able to use a function or variable before you have even declared them, or in other words: a function or variable can be declared after they have already been used.
So, to avoid any bugs, we use most of the time let, and we leave the global ones with a const receiving a certain value.
You can read more in the publication of this guy, explains straight how both new technologies inserted by ES6
By creating a variable with let, it will exist only in the scope in question. If used with the var , the variable is accessible in the rest of the code.
For example:
lista = [1,2,3,4,5,6,7,8,9];
for(let a in lista){
console.log(lista[a]);
}
//Variavel a não existirá aqui após a execução do laço
lista = [1,2,3,4,5,6,7,8,9];
for(var a in lista){
console.log(lista[a]);
}
//Variável a continua acessível mesmo após a execução do laço de repetição