Returning from a parent function from inside a child function - Javascript

I'm relatively new to coding in JavaScript, and I've came across a problem. I like to nest functions to keep things orderly, but how would I exit from a parent function from inside a child function?

example:

function foo1() {
   function foo2() {
      //return foo1() and foo2()?
   }
   foo2();
}

Solution 1:

See update under the fold

You can't. You can only return from the child function, and then return from the parent function.

I should note that in your example, nothing ever calls foo2 (As of your edit, something does). Let's look at a more real example (and one that comes up a lot): Let's say we want know if an array contains an entry matching some criterion. A first stab might be:

function doesArrayContainEntry(someArray) {
    someArray.forEach(function(entry) {
        if (entryMatchesCondition(entry)) {
            return true; // Yes it does           <-- This is wrong
        }
    });
    return false; // No it doesn't
}

You can't directly do that. Instead, you have to return from your anonymous iterator function in a way to stop the forEach loop. Since forEach doesn't offer a way to do that, you use some, which does:

function doesArrayContainEntry(someArray) {
    return someArray.some(function(entry) {
        if (entryMatchesCondition(entry)) {
            return true; // Yes it does
        }
    });
}

some returns true (and stops looping) if any call to the iterator function returns true; it returns false if no call to the iterator returned true.

Again, that's just one common example.


You've referred to setInterval below, which tells me that you're almost certainly doing this in a browser environment.

If so, your play function almost certainly has already returned by the time you want to do what you're talking about, assuming the game has any interaction with the user other than alert and confirm. This is because of the asynchronous nature of the environment.

For example:

function play() {
    var health = 100;

    function handleEvent() {
        // Handle the event, impacting health
        if (health < 0 {
            // Here's where you probably wanted to call die()
        }
    }

    hookUpSomeEvent(handleEvent);
}

The thing is, that play will run and return almost immediately. Then the browser waits for the event you hooked up to occur, and if it does, it triggers the code in handleEvent. But play has long-since returned.

Solution 2:

Make a note whether the parent function should also return.

function foo1() {
    bool shouldReturn = false;

    function foo2() {
        shouldReturn = true;    // put some logic here to tell if foo1() should also return 
        return;
    }

    if (shouldReturn) {
        return;
    } else {
        // continue
    }
}