Every javsacript developer knows that eval is evil.

But eval is really powerful and from a theoretical perspective eval is very interesting.

For instance, did you ever ask yourself in what context does eval run?

In this article, we are going to show a couple of examples that relates to this question.

Power

All the examples of this page are live and interactive code snippets:

  1. The code is executed in your browser
  2. You can modify the code and it is evaluated as you type

The interactive code snippets are powered by klipse.

Outside Scope or Inside Scope?

Usually, eval runs inside the scope of the caller function:

var context = 'outside';
(function(){
    var context = 'inside';
    return eval('context');
})();

But sometimes, eval runs outside the scope of the caller function:

var context = 'outside';
(function(){
    var context = 'inside';
    return eval.call(null, 'context');
})();

Also in this case - outside:

var context = 'outside';
(function(){
    var context = 'inside';
    return (1, eval)('context');
})();

But in this case - it’s inside:

var context = 'outside';
(function(){
    var context = 'inside';
    return (eval)('context');
})();

And another one that gets outside:

var context = 'outside';
(function(){
    var context = 'inside';
    var my_eval = eval;
    return my_eval('context');
})();

It depends whether the eval call is direct or indirect.

Furher details and explanations in this article that explains the difference between eval direct and indirect call in EcmaScript 5 and other cool stuff.