eval evaluates a javascript expression (ie a javascript string) and therefore can eval a script
eval("console.log('hello foo')");
Most functions have access to the scope where they are defined, and nothing else. But eval has access to the full scope at the point where it’s called.
eval(..) when used in a strict-mode program operates in its own lexical scope.
function foo(str) {
"use strict";
eval( str );
try {
console.log( a ); // ReferenceError: a is not defined
} catch (e) {
console.log(e.message);
}
}
foo( "var a = 2" );
var y = "global";
function test(src) {
eval(src); // may dynamically bind
return y;
}
console.log(test("var y = 'local';")); // "local"
console.log(test("var z = 'local';")); // "global"
var y = "global";
function test(src) {
(function() { eval(src) })(src); // may dynamically bind
return y;
}
console.log(test("var y = 'local';")); // "global"
console.log(test("var z = 'local';")); // "global"