Difference between eval and setTimeout execute string code

Viewed 3310

I know that eval and setTimeout can both accept a string as the (1 st) parameter, and I know that I'd better not use this. I'm just curious why is there a difference:

!function() {
    var foo = 123;
    eval("alert(foo)");
}();

!function() {
    var foo = 123;
    setTimeout("alert(foo)", 0);
}();

the first would work, and the second will give an error: foo is not defined

How are they executed behind the scene?

5 Answers

As a complement to the correct answer, here is a call to eval that would give you the same behavior, and error in this cases:

!function() {
    var foo = 123;
    window.eval("alert(foo)"); // <- note the window.eval, this is important and changes the behavior of the `eval` function
}();

!function() {
    var foo = 123;
    setTimeout("alert(foo)", 0);
}();

This blog post goes in depth on the different types of eval: http://perfectionkills.com/global-eval-what-are-the-options/

Related