Search code examples
javascripteval

Is it possible to use eval to exit a function?


I have a code similar to this.

function foo(script) {
  console.log(1);
  
  if(script) {
    eval(script);
  }
  
  console.log(2);
}

foo(/* Some expression */);

console.log(3);

I want it to print 1 and 3 but skip 2.


I tried

foo('return');

It doesn't work.


Also I tried

foo('throw new Error()')

But it skips 3 as well.


So is it possible to exit that function via eval?


Solution

  • The throw new Error() expression will work, but you will need to wrap eval(script) and all your subsequent logic inside a try/catch block:

    function foo(script) {
      console.log(1);
      
      try {
        if (script) {
          eval(script);
        }
        
        console.log(2);
      } catch(e) { }
    }
    
    foo('throw new Error()');
    
    console.log(3);