Amit Joki
Amit Joki

Reputation: 59232

why does eval() not work here?

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?

Upvotes: 3

Views: 110

Answers (1)

Murali VP
Murali VP

Reputation: 6417

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.

Upvotes: 1

Related Questions