0

Please check below 2 code snippets the difference is redeclaring as const/let and var in foo function.

for var, it executes but for const and let it throughs error.

Please tell me why it behaves differently.

Below code does not through any error as a is declared as var
var a=12; //Global variable
foo(); //hoisting 
function foo() {
    console.log("a="+a);
    var a=13;
    console.log("a="+a);
    if(true) {
        const a=89;
        console.log("in block="+ a);
    }
    var a=90;    //no error
    console.log("a="+a);    
}

Below code throughs variable declaration error "a has already been declared"

var a=12; //Global variable
foo(); //hoisting 
function foo() {
    console.log("a="+a);
    var a=13;
    console.log("a="+a);
    if(true) {
        const a=89;
        console.log("in block="+ a);
    }
    let a=90;    //Or const a :: error
    console.log("a="+a);    
}
  • 1
    With `var` you can and with `let` and `const` you can't -> "_variable shadowing /re declaration in different scope?_" But, in the case of this code `var a` outside the function is still in scope within the function - you are not shadowing but redeclaring (which is legal with `var` but not with `const` & `let`). – Randy Casburn Dec 01 '21 at 00:50
  • Thanks a lot. Now I understood the difference :) – Burak Fıçıcı Dec 01 '21 at 10:20

0 Answers0