0

I am reading Effective JavaScript. In chapter 2, Item 17: Prefer Indirect eval to Direct eval, there is the following:

"The eval function has a secret weapon: It's more than just a function. Most functions have access to the scope where they are defined, and nothing else. But eval has access to the full scope at the point where it's called. This is such immense power that when compiler writers first tried to optimize JavaScript, they discovered that eval made it difficult to make any function calls efficient, since every function call needed to make its scope available at runtime in case the function turned out to be eval

From what I understand, calling eval directly gives access to the local scope of the caller.

var x = "global";
function test() {
  var x = "local";
  return eval("x");
}
test(); // "local"

In the example above, eval has access to the local scope of the caller.

What does this have to do with the bold highlighted part of the passage I quoted from the book? I didn't understand exactly what was meant. Can someone provide a more thorough explanation of how functions make their scope available at runtime? I realize I'm being a bit vague in my question, but it's because I didn't really get the quoted passage at all. Also, how is this related to "direct eval costs dearly in performance"?

evianpring
  • 3,316
  • 1
  • 25
  • 54
  • 1
    Functions can be optimized in a variety of ways before runtime (when the script is run). Because `eval` is executed at run-time the interpreter has no way of knowing what it does, and can therefore not optimize it. The short answer: *Just don't use `eval`*; it is considered to be bad practice by pretty much everyone. – Sverri M. Olsen Dec 26 '15 at 07:09
  • I'm not sure but what it might mean is, when you define a `function`, its scope is to the parent function or window object. But when you use eval, since this function is created dynamically, current scope is set to function i.e. if in your example x was a function, it would have scope `test` and will not be available outside it. You can refer following [Fiddle](https://jsfiddle.net/683sd9fw/1/). Also refer [Why Eval is bad](http://stackoverflow.com/questions/86513/why-is-using-the-javascript-eval-function-a-bad-idea) – Rajesh Dec 26 '15 at 07:16

0 Answers0