TM. TM. - 20 days ago 7
Javascript Question

What's the difference between using "let" and "var" to declare a variable?

ECMAScript 6 introduced the

statement. I've heard it described as a "local" variable, but I'm still not quite sure how it behaves differently than the
var
keyword.

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

Answer

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 not in a block.

Also, variables declared with let are not accessible before they are declared in their enclosing block. As seen in the demo, this will throw a ReferenceError exception.

Demo: jsFiddle

Global:

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

let me = 'go'; //globally scoped
var i = 'able'; //globally scoped

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
}

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)
    }

    //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
}

Additionally (Deprecated):

let can also be used to create its own enclosing block.

function conjunctionJunctionWhatsYour() {
    //sNotGetCrazy is *not* visible out here

    let( sNotGetCrazy = 'now' ) {
        //sNotGetCrazy is only visible in here
    };

    //sNotGetCrazy is *not* visible out here
}