Javascript - eval

About

eval evaluates a javascript expression and therefore can eval a script

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

  • <note warning>''eval' will dynamically bind variable declared in the expression in the same execution scope</note>
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"

Documentation / Reference


Powered by ComboStrap