Wednesday, August 9, 2017

var vs let in JavaScript

In JavaScript, we have 2 different keywords to declare a variable: var and let. They don't have the same meaning however. Hence their different names. But what exactly is the difference between the 2?

var

The var keyword declares a function scope variable. This means, the declared variable will be available in the entire function in which is was declared and also in its enclosed functions.

let

The let keyword declares a block scope variable. This means, the variable is only known in the block that declared it, not the function. So code outside the declaring block, but inside the same function as the block, will not be able to access the variable.

Example

The example below shows a snippet of JavaScript code. The call to letTest() will result in a ReferenceError because in the letTest function, the variable y is not known outside of the if block.



var varTest = function(){
    var x = 1;
    if(x){
        var y = 2;
    }
    console.log("x = " + x);
    console.log("y = " + y);
}
console.log("varTest:");
varTest();

var letTest = function(){
    let x = 1;
    if(x){
        let y = 2;
    }
    console.log("x = " + x);
    console.log("y = " + y); //ReferenceError: y not known
}
console.log("varTest:");
letTest();