Block Scoping (Let/Const)

Let and Const

let replaces var

let uses something called block scoping - During the execution phase it is still set to undefined, but you are not allow to use it until the line is run where it declare the variable

The difference is scoping.varis scoped to the nearest function block andletis scoped to the nearest_enclosing_block (both are global if outside any block), which can be smaller than a function block.

Also, variables declared withletare not accessible before they are declared in their enclosing block.

Example 1:

function example(){
    if(true){
        var test = "whoa";
    }
    console.log(test);
}

example(); //Output "whoa"
function example(){
    if(true){
        let test = "whoa"; 
    }
    console.log(test);//Results in Reference Error 
    //We are not able to access the 'test' variable as its not part of the block 
}

example();

Example 2:

'const' behaves like 'let' but we can't redefine the value

const test = 20;
test = 5; //Result in error

results matching ""

    No results matching ""