Wednesday, October 08, 2008

Understanding eval scope. Spoiler: It's unreliable!

Today, I ran some tests to help me understand the scope in which an eval runs. Turns out, like so many things in the browser world, it's very unpredictable and exhibit different behaviors in different browsers.

Let's start with the following snippet of code. I've added comments to demarcate areas in the code, which I will be changing with each iteration.

var foo = 123;
var bar = {
changeFoo: function() {
// We'll keep changing the following snippet
eval("var foo = 456");
// Changing snippet ends


A little explanation of the code above. foo is a variable in the global scope, and it's value is set to 123. An object bar is created with a single method changeFoo which does an eval. The eval creates a local variable (thanks to the var) foo, and sets it's value to 456. bar.changeFoo is called, and the value of the global foo is alerted.

The aim is to test the scope in which eval runs. If eval is in the global scope, the global variable foo should change it's value. If eval is in the local scope, the global foo should be unaffected. Then there are various things we can do inside the changeFoo method which should keep altering the scope of this, so we are also alerting this to see what happens.

The findings are listed below:

 Changed snippetInternet ExplorerSafari 3.xFirefoxGoogle ChromeSafari Nightlies
eval("var foo=456");
window.eval("var foo=456");
this.eval("var foo=456");
eval("var foo=456", window);
(function() {
eval("var foo=456");
(function() {
window.eval("var foo=456");
with(window) {
eval("var foo=456");
with(window) {
window.eval("var foo=456");

What I think of these results:

  • I don't know what Firefox is doing in case 2, and for some reason Safari Nightlies seem to be following it. Maybe it's just beyond my understanding, but case 2 is not supposed to be different from case 1. Why does case 2 operate in global scope? If window.eval is different from eval, case 3 shouldn't all have given errors. Someone please help me understand that $hit.
  • Case 4 makes sense, but that's a non-standard behavior in Firefox. Understandable that no one else exhibits it.
  • IE baffles me in case 5, and Chrome seems to ape it. In this scenario, the anonymous function is supposed to have the global scope - so, in this case, this should point to the window. WTF is happening here!
  • Consistent with case 2 above, Firefox and Safari Nightlies continue to display weird behavior in case 6. For some reason, in these two cases, the eval operates in the global scope.
  • Now, I have no idea why, but only cases 8 and 9 seem to really work at all. This is despite Doug Crockford going on and on about not using with constructs. It's also despite being beyond (my) understanding about why the with should make any difference to the eval, since eval is part of the window object.

All in all, if you are going to be evaling JavaScript (not JSON), and you want the eval'd code to run in the global scope, you should use the with block around the JavaScript snippet. Or else, you can lose a lot of hair handling cross-browser issues.

Hope you don't lose as much hair as me.


Anonymous said...

Thanks for sharing your findings. However for me in Firefox 3 variation 7 and 8 only work as expected if foo exists in global scope at the time the string is eval'd. Otherwise it will just put foo into local scope.
Can anybody confirm this behavior?

xero said...

IE is handling case 5 more like I'd think. I couldn't find the docs on anonymous function scope and ownership so I can't say if its correct, but I'd think it would be part of its containing scope, like a method.

Rael said...

Interesting... I was looking for a way to run eval in global scope from within objects, but didn't think of using 'with'. Nice to know it's possible after all.

As for case 2... it seems that in FF's case, window.eval isn't the same as eval. (window.eval !== eval)
And eval isn't a standard method on objects (anymore?), which explains 3 vs 2.

Another case you could've tested is or eval.apply
they turn out the same as window.eval though.
And as an oddity, FF doesn't allow, ...) (same with apply).

(I don't have Safari nightly though, so can't account for any of this there)

Anonymous said...

I use

with (this) {
// some code

it seems to work - usually anyway

Oliver said...

Firefox 3 and Safari nightlies both follow the ES4 semantics for eval, that is "eval" on its own acts in the scope it is used within, whereas globalObject.eval acts in the global scope.

Neither allows aliases to eval anymore.

Rakesh Pai said...

anonymous1: You might be right. Will get back to you.

xero: A bug in JavaScript ensures that private functions run on the global scope, even if they have access to the constructor's variables through a closure. It's not what you'd expect, but that the way the language is.

rael: I don't think eval was ever supposed to be a standard method on objects. In fact, now that I think of it, case 3 proves nothing really.

anonymous2: From everything I know, you are not achieving anything by enclosing your code in the with statement.

oliver: You indeed seem right, going by my observations. It doesn't help in today's world, but maybe it's the right thing for the future.

shogun70 said...

If foo isn't declared in the global scope all your tests will (should) only set it in the local scope. Thus the final alert(foo) will throw.

If you want to execute some script in the global scope you should use dynamic script insertion.

If you want to evaluate some code outside of the local scope - so that local variables don't bleed in - then call eval indirectly via another function. e.g.

function evalScript() {
return eval(arguments[0]);

Jerry said...

Good one. :)

Anonymous said...

i think that a timeout runs in global scope, and wrapping its contents in a "quotes" means that it will run the code as an eval.

obviously this has its downsides that it will run at the end of your current running block of code, not at the exact time that it is set (eve if a time of 0 is specified) but it will defiantly in all browsers run in the global scope (and may fix any problem you were looking to solve)


jerone said...

There is also a difference between

eval("var foo = 456");


eval("foo = 456");

BeaKeR said...

Found a related Ajaxian post from a year ago:

Anonymous said...

This is the best way to solve the eval problem:

if (window.execScript) window.execScript(sCode); //ie
else top.eval(sCode); //others


Cesar said...

For a more generalized solution with tests take a look at:

PatchMonster said...

I don't have the browsers on hand to test this, but is the immediate calling environment accessible to eval?

Example, should return 10:

function foo() {
var bar = 2;
eval("bar = 10");
return bar;

I'm wondering if some quirky browsers might place eval in an isolated environment (or to some random degree). Thank you for the work you've done so far.

automotive hand tools said...

Tomorrow I will run a test too. I will show you my results... the information that you have here its very important...
thank you

Beth T. Cormier

vertigo symptoms causes said...

This is a very interesting topic ,if possible id like to know if you could provide me with a little more data on this.

kolinahr said...

I've been using this version for years. It works everywhere.
The magic is in the intermediate variable realGlobal.

function globalEval(src) {
var realGlobal = this;
if (window.execScript) // eval in global scope for IE
else // other browsers

This also works, and is even simpler:

function globalEval(src) {
if (window.execScript) // eval in global scope for IE
else // other browsers, src);

Randy Hudson said...

If the eval is really happening in the global scope, then not only would "var foo=456" modify outer foo, but you could also declare a new global var visible after the eval completes. Change the snippet to:
"var foo=456, baz=789"

and the post-eval alert to:


and you'll find that the ONLY way to do a global eval in IE7 (when this artical was written) is to use window.execScript.

Wizzart said...

some tests with scope. When may we use this example with "indirrect" eval???

no one said...

do you might want to

examine when it

comes to nations

straight away probably in ingestion. everyone really are the right not to mention major


study international consultancies with

regard to India with higher visa certainty. we boost you might when it comes to handling these f1 abroad education consultants in hyderabad visa for you in particularly shorter period. a number of us actually


also aid a person will because of files necessary to request for the varsity


pasha said...

for an additional pair intake do you need explore for worldwide. decent visa self-belief is simply a lot

of our main mobile and we are positioned because prime international consultancies located in asian countries. throughout genuinely a shorter time that we facilitate

you to report ones own fone visa. when it comes to the united states if you almost any details of educational

facilities and furthermore univerisity we will aid you to overseas education consultants in himayat nagar.