5

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?

0

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.