Search code examples
javascripteval

Javascript return in eval string


I know eval is evil, but in this case please do not point this out please. I am creating something very custom and in my case eval is the only solution (that is what eval is there for).

My problem is that return does not work in eval strings. The browser throws and Illegal return statement error. Could someone explain to me why this happens?

I would like this string to be eval'ed:

eval(`
  console.log('log this');
  return;
  console.log('DONT log this')
`);

Here is a stack blitz to play with

https://stackblitz.com/edit/angular-8x8p6m?file=src%2Fapp%2Fapp.component.ts


Solution

  • Try inputting console.log('log this'); return; console.log('DONT log this'); in your browser (that's basically what eval is); it'll complain because you're trying to use return outside of a function.

    However, you can do something like this:

    eval(`
      (() => {
        console.log('log this');
        return;
        console.log('DONT log this');
      })()
    `);