eloquent javascript chapter regarding modules. On scopes and eval function

184 views Asked by At

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?

1

There are 1 answers

4
Travis Kaufman On BEST ANSWER

Eval has some tricky semantics. From mdn:

If you use the eval function indirectly, by invoking it via a reference other than eval, as of ECMAScript 5 it works at global scope rather than local scope; this means, for instance, that function declarations create global functions, and that the code being evaluated doesn't have access to local variables within the scope where it's being called.

So in your case, because you're calling eval directly within that function, it defines x within the lexical scope of that function, not available to the global scope. However, if you were to do something like this:

var _eval = eval;

function e() {
    _eval("var x = 2");
    return x;
}

console.log(e());
console.log(x);

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