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

Asked

Viewed 24,661 times

78

Since the word was introduced let in the Ecmascript I have only heard about it, so far I have not seen any practical example and to be honest I do not know very well what is a variable let and how it behaves. The only thing I understood, and very 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?

  • In addition to everything you’ve read about the block scope, Let also lacks the HOISTING behavior that var has, which basically "throws" the variable to the top of the code, even when it was declared further down

6 answers

89


There is a difference in scope.

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

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

But this was not enough, it needs to have a block scope. The let was created, and is available in newer versions of the language precisely 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 in the Github for future reference.

Documentation of let.

const can be used in newer versions of the language and equates to let only it’s a constant.

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

When possible to use generally, the let is preferable, the narrower scope is always preferable. Although if you keep your functions as small as you say "good practices" it won’t make so much difference to use one or the other. And indeed sometimes the var is a hand on the wheel when you need the "live" value after finishing a scope (not that you can’t do with let also).

There is another reason for the let be created is to resolve a matter of creating your own references in closures, they couldn’t change the semantics of language into something that already existed, they created something new, so the new semantics would be opt-in. Let’s take 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 up to global, but gives in it), so the capture of a closure takes a reference to that variable which is considered universal for the 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 forwards, Chrome since 49 (41 in strict mode, from 4 to connect manually), Safari 11 and others based on them, prefer the let. IE 11 accepts the let, but does not treat the closure correctly. Or wherever it doesn’t work the person is already used to a lot of things going wrong.

Just remember that if you use the let must use some transpilator that generates code that is more suitable for older versions, or to be absolutely sure that your page will never be accessed by older browsers. Ensuring this, in general, should always prefer the let. The var stays to rotate in browsers that you won’t run a Babel or something.

35

let and var have many similarities but some important differences.

Differences:

- let does not export to global

A declared global scope variable with let is not exported as a whole.

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 that when used overrides/re-starts the variable and makes it available within the scope of the function in which it is, 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-declare a variable with letin 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 next line

With 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 that would be a mistake.

I mean, this works:

console.log(x); // undefined
var x = 'foo';

but this makes a mistake:

console.log(x); // Uncaught ReferenceError: x is not defined
let x = 'foo';

26

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 inverse of the 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

9

Well, fundamentally speaking, var and let are modifiers of the scope scope of the variable, that is, define how far it is possible to reference such a variable within the scope in question.

Explanations

Modifier var

As most of you already know, var serves to make the variable local, accessible only to its function scope, because if you declare a variable without any modifier it ends up having its scope scope as a global variable, ie you can 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 ends up being accessible in any execution context, now for variables assigned with the modifier var are accessible only to their current execution context.

Modifier let

Already the let causes the variable’s scope to declare to abstain from the code block 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.
}

Note that the variable assignment y for the value 3 out of the if expression only holds for the log that is outside the if expression, the variable assignment y for the value 4 within the if expression, only the log inside the if expression is valid. This gives to understand that the let only declares a variable for use in your block/expression, so within the if expression it no longer had the same context.

Completion

The difference between var and let simply specify the scope of the variable in question.

Sources/References:

7

Complementing the response of friends, it is always good you use LET instead of VAR, to avoid the so-called Hoisting, what is this ?

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 overall scope or 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 mostly use Let, and leave the global ones with a const getting a certain value.

you can read more in the publication of this guy, explains how it works both new technologies inserted by ES6

Medium

6

Creating a variable with Let, it will exist only in the scope in question. Use 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.