Search code examples
javascriptfunctiongoto

Breaking out of one JS function to call another JS function


Let's say that I have a series of functions:

function a(){
   //do this, do that
   b();
}
function b(){
   //do this, do that
   c();
}
function c(){
   //do this, do that
   // program ends at this point
}
a();

You would assume that from executing the code, we go from a() to b() to c() and the program terminates...

What I'm wondering is... is it possible to place code somewhere within the // do this, do that part of b() that depending on certain conditions to return to a() and then proceed through without the need of returning where it left off in b(), although if needed could then launch b() afresh?

I know, what you're thinking... "This is a JavaScript GOTO question, surely!" and to a degree it is... but seriously, is it possible to break from a function A completely and go to function B without having to worry about it returning to function A to finish where it left off?


Solution

  • You can use JavaScript's return statement like this

    function a(){
       //do this, do that
       b();
    }
    function b(){
       if (some_random_condition) {
          return;
       }
       c();
    }
    a();
    

    The return statement makes it possible to go to a without having to execute the rest of b function.