In javascript, it's possible to store code as string and execute it with 'eval'. On the other hand, we can represent code as a function for further execution. Why is preferable to use closures over 'eval' in javascript?
EDIT:
For example:
Code stored as string:
function(x, y, callback){
if (x > y){
eval(callback);
}
}
Code stored as function:
function(x, y, callback){
if (x > y){
callback();
}
}
eval
itself does not create a closure and does not provide encapsulation. It is merely a means to evaluate JavaScript code represented as a string.
If you use eval
to execute a function (like your example does), it will not modify the scope of that function nor the closure created by that function. Regardless of eval
, functions always execute in the scope in which they were originally declared and they always create a closure (which encapsulates any declarations made within that function).
There's only one minor nuance involving scope and eval
. If you invoke eval
directly it will use the local scope. If you invoke eval
indirectly, it will use the global scope.
Example from MDN:
function test() {
var x = 2, y = 4;
console.log(eval('x + y')); // Direct call, uses local scope, result is 6
var geval = eval; // equivalent to calling eval in the global scope
console.log(geval('x + y')); // Indirect call, uses global scope, throws ReferenceError because `x` is undefined
}