How to execute Javascript code ? Ie How to eval ?

About

eval evaluates a javascript expression (ie a javascript string) and therefore can eval a script

Example

eval("console.log('hello foo')");

Management

Scope

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.

Strict

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" );

Variable Binding

  • ''eval' will dynamically bind variable declared in the expression in the same execution scope
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"
  • to avoid it, the scope must be restraint by using an iife
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"

1)


Powered by ComboStrap