What is the difference between declaring variables using let and var?

63

Since the word let was introduced in ECMAScript I have only heard about it, so far I have not seen any practical examples and to be honest I do not know very well what a let variable is and how it behaves. The only thing I understand, and very superficially, is that it serves to declare a local variable, something related to scope.

What are let variables? What are they for? When to use them instead of var ?

    
asked by Renan 16.01.2015 в 13:56
source

4 answers

69

There is a scope difference.

You should know that any "declared" variable without let , var , or const has global scope, valid for all script .

You may know that you should always use var to make the scope local, ie it is only valid within the function where it was declared (it can be global if it is not within function).

But this was not enough, it needs to have a one-block scope. let has been created, and is available in newer versions of the language just to provide this more limited scope.

Examples:

function exemplo() {
    //x poderia ser acessado aqui
    for(var x = 0; x < 5; x++) {
        //x existe aqui
    };
    //x está visível aqui novamente
};
function exemplo() {
    //x não existe aqui
    for(let x = 0; x < 5; x++ ) {
        //x existe aqui
    };
    //x não está visível aqui novamente
};

let documentation.

const can be used in newer versions of language and is equivalent to let only that is a constant.

As it is not any browser that supports these newer commands, they should be avoided.

When you generally use let is preferable, the narrowest scope is always preferable. Although, if you keep your functions as small as you say "good practices" it will not make so much difference to use one or the other. And in fact sometimes var is a hand on the wheel when it needs the "live" value after the end of a scope (not that it can not do with let also).

    
answered by 16.01.2015 / 14:03
source
24
  

let and var have many similarities but some important differences.

Differences:

- let does not export to global

A global scope 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% w / o%, which when used overlaps / re-starts the variable and makes it available within the scope of the function it is in, var is more refined / detailed and allows block-scoping differences. This is valid for blocks let , if , for 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-declare a variable with while in the same scope gives error

If we re-declare a variable twice in the same scope var give error. This prevents errors that are difficult to detect.

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 on the next line

With let 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 var . With undefined 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';
    
answered by 19.04.2016 в 14:36
22

As described in MDN :

  

let allows you to declare variables by limiting their scope to the block, statement, or an expression in which it is used. This is inverse of the keyword var, which defines a variable globally or in the integer scope of a function, regardless of the block scope.

A very simple example using the for loop:

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
    
answered by 16.01.2015 в 14:03
5

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:

answered by 19.12.2017 в 17:40