Lets vs Vars

March 2014

Recently while trying to figure out the difference between vars and lets in Swift Google autocomplete offered up 'javascript' as a suggestion. Surprisingly, javascript also has lets and vars! The difference between them comes down to scope.

@ThinkingStiff did a great job of explaining it on Stack Overflow:

Globally:


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

Function:


function ingWithinEstablishedParameters() {
    let terOfRecommendation = 'awesome worker!'; //function block scoped
    var sityCheerleading = 'go!'; //function block scoped
};

Block:

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