Home > Blockchain >  isn't the variable declared outside with let global variable too?
isn't the variable declared outside with let global variable too?

Time:10-29

I am trying to understand new Function syntex. when i declare variable 'value' using let it gives 'ReferenceError: value is not defined' error but if i use var or without var the output is printed as test. I assume that the 'value' variable is global because it is defined outside. But why does it work with var but not let although both are global variable.??

let value = "test";
    function getFunc() {
        // value = "test";
    
        let func = new Function('console.log(value)');
    
        return func;
    }
    
    getFunc()();

CodePudding user response:

At the top level, let, unlike var, does not create a property on the global object.

var foo = "Foo";  // globally scoped
let bar = "Bar"; // not allowed to be globally scoped

console.log(window.foo); // Foo
console.log(window.bar); // undefined

Reference

Therefor let may only be used inside of an enclosed block denoted by {}.

  • Related