2

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

1
  • 1
    Return statements are only valid inside functions. Commented Nov 16, 2018 at 12:40

4 Answers 4

3

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');
  })()
`);
Sign up to request clarification or add additional context in comments.

1 Comment

Most simplified answer. Thank you.
2

This is why we use new Function() instead of eval() if we really need eval() for something.

If you pass a string to the Function constructor, it will automatically call eval() on it. So no need to wrap eval And function in the same statement, that's basically doing the same thing twice.

const js_str = `
  console.log('log this');
  return 'ok';
  console.log('DONT log this')
`;

const result = new Function( js_str )();

console.log( result );

If you could explain what you're creating with eval(), there might even be a better solution as well.

1 Comment

Eval is faster to use is this case don't you think?
1

Your problem is that you're not in a function:

eval('(new Function("console.log(1);return;console.log(2)"))()');

Logs 1 but not 2.

Comments

1

As mentioned in the comments, return statements are only valid inside functions

Give this a try:

eval('(function (){ 
  console.log("log this");
  return 23;
  console.log("do not log this"); 
})()');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.