3

First of all

I know eval() is evil, but this is a theoritical question.

Suppose I have a loop:

function loop() {
    for(var i = 0 ;i <= 10; i++) {
        $('ul').append('RUN :' + i + '<br>');
            eval('break;');
    }
}

while just putting break; in the place of eval() it works, but when same is done using eval('break;'), it results in a error "Uncaught SyntaxError: Illegal break statement"

Also, i know to break the loop, I can use:

return false;

But why this behavior at first place?

Community
  • 1
  • 1
Amit Joki
  • 58,320
  • 7
  • 77
  • 95
  • 1
    [Some](http://stackoverflow.com/questions/6684046/javascript-eval-method) possible [duplicates](http://stackoverflow.com/questions/11961963/cant-eval-break-statement). – Lix Mar 16 '14 at 16:36
  • 1
    It's not the loop, just doing `eval('break;')` gets you the same error, as break shouldn't be eval'ed – adeneo Mar 16 '14 at 16:36
  • @adeneo, my question is why? – Amit Joki Mar 16 '14 at 16:37
  • 1
    Because it's a statement, and what good would it do to eval a statement and return the result, the `break` statement has no context in `eval()`, so it's an error, it's like just randomly typing `break` somewhere. – adeneo Mar 16 '14 at 16:37
  • Because you're just evaling a `break` in the middle of nowhere, like if you just typed `break` in the console. – Dave Newton Mar 16 '14 at 16:38
  • Okay. So guys, please post it as answer so i can accept it – Amit Joki Mar 16 '14 at 16:39

1 Answers1

1

eval-ed code's context is in the same namespace as that of the caller, so variables, functions etc. are available for the code in eval, but not the program structure itself.

Murali VP
  • 6,198
  • 4
  • 28
  • 36