Etienne
Etienne

Reputation: 73

How to stop a function containing another function from the contained function in javascript?

Sorry for the title, but I did not found a simple one.
I have a long function: function testa().
Running this function I call several times another one: function testb().
When function testb() returns "false", I would like to stop function testa() too before the end of the function.

Thank you for helping ;)

Here is an example:

function testb(){
if (blabla.test(val)) { 
    return true;           
}
else {
    return false;
}


function testa(){
blabla
blabla
function testb()// if function testb() return false, stop function testa() here, else continue function testa()
blabla
blabla
blabla
blabla
blabla
function testb() // if function testb() return false, stop function testa() here, else continue function testa()
blabla
blabla
blabla
function testb()// if function testb() return false, stop function testa() here, else continue function testa()
blabla
blabla
blabla

return
}

Upvotes: 1

Views: 53

Answers (3)

Pankaj Shukla
Pankaj Shukla

Reputation: 2672

You can simply return from function testa so that further code is not executed.

function testb(){
if (blabla.test(val)) { 
    return true;           
}
else {
    return false;
}

function testa(){
blabla;
blabla;
if(!testb()) {
   return;
}
blabla;//continue here
blabla;

}

Upvotes: 2

Slawa Eremin
Slawa Eremin

Reputation: 5415

You can use "return" to end function:

function testa(){
  bla
  bla

  if (!testb()) return;
  
  bla
  bla

  if (!testb()) return;

  bla

}

Upvotes: 1

eBourgess
eBourgess

Reputation: 303

you can nest them in the testa if statement, and use break; to stop the function

EDIT

By that I meant like this:

if(!testb){
break;
}

Upvotes: 1

Related Questions