1

Put the code in the file(test.js), then execute node test.js. You'll get:

ReferenceError: val is not defined

If you copy the code directly in the node environment (or a browser console), no error is reported.

let val = "global"

function foo2() {
    let val = "local"
    let f = eval
    return f("val")
}
foo2()
Dmitry
  • 5,646
  • 14
  • 33
  • 35
  • "local" does not constitute code, it's just a string. "The eval() function evaluates JavaScript code represented as a string." https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval – Dexygen Dec 26 '18 at 08:52

1 Answers1

3

If you read through the MDN page on eval you will see:

if you use the eval function indirectly, by invoking it via a reference other than eval, as of ECMAScript 5 it works in the global scope rather than the local scope.

When you run this code in Node, it will look on the global object for val and won't find it because even variables declared on the outside scope are private to the enclosing module in Node - they don’t end up in the global namespace unless you put them there. This causes it the error you noticed.

This, however, will log global in Node:

global['val'] = "global"

function foo2() {
  let val = "local"
  let f = eval
  return f("val")
}
console.log(foo2())
Mark
  • 74,559
  • 4
  • 81
  • 117
  • But why does it only works if you put it explicitly into `global` and not with `let val`? – Dmitry Dec 26 '18 at 09:17
  • @Dmitry because in Node everything is in a module. Variables don't end up in the global scope unless you explicitly put them there. (Not that I'm recommending it), but you can also assign a variable with no `let` or `var` and it will be global too (and the indirect eval above will work). There's a good discussion [here](https://stackoverflow.com/questions/15287201/where-are-vars-stored-in-nodejs) – Mark Dec 26 '18 at 09:19
  • So the problem is that `val` is local to the `test` module and `eval` runs on global scope because of it is used indirectly. Clould you add this to your answer for better explanation? – Dmitry Dec 26 '18 at 09:28