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())