Eloquent javscript writes this in chapter 10 of the modules chapter:
The most obvious way is the special operator eval, which will execute a string of code in the current scope. This is usually a bad idea because it breaks some of the sane properties that scopes normally have, such as being isolated from the outside world.
Here is the code:
function evalAndReturnX(code) {
eval(code);
return x;
}
console.log(evalAndReturnX("var x = 2"));
console.log(x)
console.log(code)
it outputs:
2
ReferenceError: x is not defined (line 7)
which seems normal? What gives? I don't see any violation of scope?
Eval has some tricky semantics. From mdn:
So in your case, because you're calling
eval
directly within that function, it definesx
within the lexical scope of that function, not available to the global scope. However, if you were to do something like this:It would work in both cases, since this would define
x
in the global scope, which would be inherited by the lexical scope of the callee.See this fiddle for a working example