0

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()();
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Anonymous
  • 318
  • 4
  • 14
  • see: [var](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var), and [let](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let). Both documents do contain a simple example. – Luuk Oct 29 '21 at 05:44

1 Answers1

0

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

whatever.idc
  • 92
  • 1
  • 1
  • 10