ReferrenceError while trying to access variable inside of Function constructor

Viewed 68

Reading the mdn documentation on the difference between Function constructor and function declaration. The example specified there works on the browser and also on the node.js repl, but on trying it through a file, the node.js process crashed with this error

ReferenceError: x is not defined

This is the program

var x = "bar";

function test() {
    var x = "baz";
    return new Function("return x;");
}

var t = test();
console.log(t());

What might be the possible reason for this example not work as expected when been executed from a file with node.js?

1 Answers

In the Node REPL, the lexical location of where you're typing in code is the top level, equivalent to typing stuff into the top of a <script> tag in the browser.

Variables defined with var on the top level get assigned to the global object. So, in both Node's REPL and the browser, your

var x = "bar";

results in x being assigned to the global object.

But, in contrast, when you run the code from a file, eg node bar.js, the code that is run is inside a module - it's not on the top level, so variables declared at the top level of such a script do not get assigned to the global object.

The function that is created is global, at the top level, so it can only lexically "see" variables defined at the top level. So, when running the code as a file in Node, since the scope of the code being run is not the top level, the created function can't see x anywhere, so a ReferenceError is the result.

Related