Let

Welcome to the magical world of let!

let greeter = "Say hi!";
let times = 4;

if(times > 3) {
    let greeter = "Hello world";
    console.log(greeter);        //"Hello world"
}

console.log(greeter);            //"Say hi!"

What's the difference between Let and Var???

Let is block scoped

Let locks the declarations within the block of code. In the example above, the declaration within the if statement stays within the statement. Outside of the block, it is still defined as "Say hi!".

Let can be updated but not redefined

let greeter = "Say hi!";
let greeter = "Hello world";    ////error: Identifier 'greeting' has already been declared

let variables cannot be redefined.

let greeter = "Say hi!";
greeter = "Hello world";

However, we can get around the problem like this. Why does this work? the second line overrides the let statement and redefines it as a global variable.

Let hoisting

Let also gets hoisted to the top like var. If you try to use a let variable before declaration, you'll get a Reference Error.

results matching ""

    No results matching ""