0

If i am ina function which was called from inside another function, how do I exit out of the main/parent function?

e.g:

function(firstFunction(){
    //stuff
    secondFunction()
    // stuff if second function doesnt exit
}

function secondFunction(){
    if( // some stuff here to do checks...){
        /***** Exit from this and firstFunction, i.e stop code after this function call from running ****/
    }
}
1
  • You don't, without a little bit of workaround. There's no direct way. Commented Oct 16, 2013 at 11:10

4 Answers 4

2

The other answers are obviously correct, but I'd differ slightly and do it this way...

function firstFunction() {
    if (secondFunction()) {
        // do stuff here
    }
}

function secondFunction() {
    if (something) {
        return false;  // exit from here and do not continue execution of firstFunction
    }
    return true;
}

It's just a difference of opinion in coding styles really, and will have no difference to the end result.

Sign up to request clarification or add additional context in comments.

Comments

1

You can return some value to indicate that you want to exit from the firstFunction().

e.g.

function(firstFunction(){
    //stuff
    rt = secondFunction()
    if (rt == false) {
        return; // exit out of function
    }
    // stuff if second function doesnt exit
}

function secondFunction(){
    if( // some stuff here to do checks...){
        /***** Exit from this and firstFunction, i.e stop code after this function call from running ****/
        return false;
    }
    return true;
}

2 Comments

This is a decent way.
Note that without a return true in the secondFunction, undefined will be returned, which means !rt will always be true, and the firstFunction will always exit.
1

You cannot directly return control flow 2-steps up the stack. However you could return a value from your inner function which is then handled in the outer. Something like this:

function(firstFunction(){
    var result = secondFunction()
    if (!result) 
        return
}

function secondFunction(){
    if( /* some stuff here to do checks */ ){
        return false;
    }
    return true;
}

Comments

1

you should do a callback like this:

function firstFunction () {
  secondFunction(function () {
    // do stuff here if secondFunction is successfull
  });
};

function secondFunction (cb) {
  if (something) cb();
};

this way you can do asyncronous stuff in secondFunction too like ajax etc.

1 Comment

+1 for an alternative method. I can't think of why I'd ever use it, but I like it :D

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.