Javascript - eval

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > ECMAScript - Grammar Standard

1 - About

eval evaluates a javascript expression.

Advertising

3 - Management

3.1 - 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.

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

3.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"

Advertising

4 - Documentation / Reference

web/javascript/es/eval.txt · Last modified: 2019/02/16 17:40 by gerardnico