javascript tutorial - [Solved-5 Solutions] Let and Var - javascript - java script - javascript array



Problem:

What are the differences ? When should let be used over var ?

Solution 1:

The difference is scoping. var is scoped to the nearest function block and let is scoped to the nearest enclosing block, which can be smaller than a function block. Both are global if outside any block.

let me = 'go';  // globally scoped
var i = 'able'; // globally scoped
click below button to copy the code. By JavaScript tutorial team

However, global variables defined with let will not be added as properties on the global windowobject like those defined with var.

console.log(window.me); // undefined
console.log(window.i); // 'able'
click below button to copy the code. By JavaScript tutorial team

Function:

They are identical when used like this in a function block.

function ingWithinEstablishedParameters() {
    let terOfRecommendation = 'awesome worker!'; //function block scoped
    var sityCheerleading = 'go!'; //function block scoped
}
click below button to copy the code. By JavaScript tutorial team

Block:

Here is the difference. let is only visible in the for() loop and var is visible to the whole function.

function allyIlliterate() {
    //tuce is *not* visible out here

    for( let tuce = 0; tuce < 5; tuce++ ) {
        //tuce is only visible in here (and in the for() parentheses)
        //and there is a separate tuce variable for each iteration of the loop
    }

    //tuce is *not* visible out here
}

function byE40() {
    //nish *is* visible out here

    for( var nish = 0; nish < 5; nish++ ) {
        //nish is visible to the whole function
    }

    //nish *is* visible out here
}
click below button to copy the code. By JavaScript tutorial team

Redeclaration:

Assuming strict mode, var will let you re-declare the same variable in the same scope. On the other hand, let will not:

'use strict';
let me = 'foo';
let me = 'bar'; // SyntaxError: Identifier 'me' has already been declared
'use strict';
var me = 'foo';
var me = 'bar'; // No problem, `me` is replaced.
click below button to copy the code. By JavaScript tutorial team

Solution 2:

let can also be used to avoid problems with closures. It binds fresh value rather than keeping an old reference as shown in examples below.

DEMO

for(var i = 1; i < 6; i++) {
  document.getElementById('my-element' + i)
    .addEventListener('click', function() { alert(i) })
}
click below button to copy the code. By JavaScript tutorial team
  • Code above demonstrates a classic JavaScript closure problem. Reference to the i variable is being stored in the click handler closure, rather than the actual value of i.
  • Every single click handler will refer to the same object because there’s only one counter object which holds 6 so you get six on each click.
  • General workaround is to wrap this in an anonymous function and pass i as argument. Such issues can also be avoided now by using let instead var as shown in code below.

DEMO (Tested in Chrome and Firefox 50)

'use strict';

for(let i = 1; i < 6; i++) {
  document.getElementById('my-element' + i)
    .addEventListener('click', function() { alert(i) })
}
click below button to copy the code. By JavaScript tutorial team

Solution 3:

The accepted answer is missing a point:

{
  let a = 123;
};

console.log(a); // ReferenceError: a is not defined
click below button to copy the code. By JavaScript tutorial team

Solution 4:

let is interesting, because it allows us to do something like this:

(() => {
    var count = 0;

    for (let i = 0; i < 2; ++i) {
        for (let i = 0; i < 2; ++i) {
            for (let i = 0; i < 2; ++i) {
                console.log(count++);
            }
        }
    }
})();
click below button to copy the code. By JavaScript tutorial team
  • Which results in counting [0, 7].
  • Whereas
(() => {
    var count = 0;

    for (var i = 0; i < 2; ++i) {
        for (var i = 0; i < 2; ++i) {
            for (var i = 0; i < 2; ++i) {
                console.log(count++);
            }
        }
    }
})();
click below button to copy the code. By JavaScript tutorial team
  • Only counts [0, 1].

Solution 5:

  • It also appears that, at least in Visual Studio 2015, TypeScript 1.5, "var" allows multiple declarations of the same variable name in a block, and "let" doesn't.
  • This won't generate a compile error:
var x = 1;
var x = 2;
click below button to copy the code. By JavaScript tutorial team
  • This will:
let x = 1;
let x = 2;
click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - Let and Var