Table of Contents

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

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"

1)