Search code examples
javascriptfunctionsecurityeval

eval vs function constructor


I was reading about eval on MDN and it seems to suggest that a somewhat "better" alternative to eval is to use a function constructor. MDN seems to highlight that using a function constructor is less of a security risk compared to eval as:

a third-party code can see the scope in which eval() was invoked, which can lead to possible attacks in ways to which the similar Function is not susceptible.

- MDN

What exactly does "a third-party code can see the scope in which eval() was invoked" mean and how does it impact the security of my JS apps?


Solution

  • From the MDN page:

    However, unlike eval, the Function constructor creates functions which execute in the global scope only.

    If you wrap all of your code in a closure, secret objects cannot be accessed from the evaluated function body.

    (() => {
      let secret = 42;
      eval("console.log(secret)"); // 42
      let fn = new Function("console.log(secret)");
      fn(); // secret is not defined
    })();