Search code examples
functionglobalnew-operatorvarreferenceerror

Isn't the variable declared outside with let global variable too?


I am trying to understand new function syntax.

When I declare variable 'value' using let it, I get an error

ReferenceError: value is not defined

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()();

Solution

  • 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 {}.