1

Something seems wrong with the following code. It declares a function with eval, calls it — until then, everything is fine — and, calls it again but, though a function and thus gets an error.

var fn = function() {
    return isTwo(2);
};
var check = function() {
    eval("var isTwo = function(value) { return value == 2 }")
    console.log(isTwo(2)); // returns true
    console.log(fn()); // returns isTwo is not defined
}
check();

Unwrapping the check function made things works, but seems wrong. Why using eval inside of a function should change its behavior?

var fn = function() {
    return isTwo(2);
};

eval("var isTwo = function(value) { return value == 2 }")
console.log(isTwo(2)); // returns true
console.log(fn()); // returns true
yves amsellem
  • 7,106
  • 5
  • 44
  • 68
  • `isTwo` is not in scope in `fn` in the first code. – elclanrs Mar 13 '16 at 23:13
  • Don't use `eval` to declare variables. It's bad practice, and forbidden in strict mode. – Oriol Mar 13 '16 at 23:18
  • @Oriol you don't know what I'm trying to achieve, so you may point out some article in the eval is evil direction, but you may weight your words ^^ http://stackoverflow.com/questions/197769/when-is-javascripts-eval-not-evil – yves amsellem Mar 13 '16 at 23:21
  • @yvesamsellem I didn't say `eval` is evil. `eval` is dangerous, but useful if you know what you are doing. However, using it to declare variables is not allowed in strict mode. You are only able to do it because due to backwards compatibility it was impossible to kill sloppy mode. – Oriol Mar 13 '16 at 23:24

1 Answers1

2

Because eval acts as if you had replaced the line with the code to be evaluated. Therefore, var isTwo = function(value) { return value == 2 } defines a local variable, and it can't be accessed by your other function. The reason it works in the outer block is because it is then a global variable, and can be accessed by your other function.

Majora320
  • 1,321
  • 1
  • 13
  • 33