4

The execution of this script: tmp.js, that contains:

var parameters = {};
(1,eval)("var parameters = {a:1}");
(1,eval)(console.log(parameters));

node tmp.js

produces:

{}

If we comment out the first statement, and execute again the script, we obtain:

{ a: 1 }

The global scope contains exactly the same variables with the same value, so why console.log displays a different value?

1
  • 2
    That last line was probably meant to be either console.log(parameters) or (1,eval)("console.log(parameters)"). But don't change it now, it would invalidate the answers you've received. Commented Apr 6, 2018 at 11:05

1 Answer 1

5

Because all code you run in Node is running in a Node module,¹ with its own scope, not at global scope. But the way you're calling eval (indirectly, (1,eval)(...)) runs the code in the string at global scope. So you have two parameters variables: A local one in the module, and a global one. The local one wins (when it exists).

var parameters = {};                // <== Creates a local variable in the module
(1,eval)("var parameters = {a:1}"); // <== Creates a global variable
(1,eval)(console.log(parameters));  // <== Shows the local if there is one,
                                    //     the global if not

Your last line of code is a bit odd: It calls console.log, passing in parameters, and then passes the return value (which will be undefined) into eval. Not much point in that call to eval with undefined.

If that last line were

(1,eval)("console.log(parameters)");

...it would run at global scope, not module scope, and always show the global.

Here's an example that does the same thing without Node:

(function() {
  var parameters = {};
  (1,eval)("var parameters = {a:1}");
  console.log("local", parameters);
  (1,eval)('console.log("global", parameters);');
})();


¹ FWIW, according to the documentation, your code is wrapped in a function that looks like this:

(function(exports, require, module, __filename, __dirname) {
// Module code actually lives in here
});

...and then executed by Node.

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.