7

How can I use return in javascript

function hello1() {

    function hello2() {

        if (condition) {
            return; // How can I exit from hello1 function not hello2 ?
        }

    }

}
2
  • you mean exit from hello2 not hello1 Commented Dec 7, 2010 at 17:02
  • 2
    I guess this depends how you are calling hello2, hello2 can't be executed until you have an object back from hello1. I think you're going to have to post a more accurate example of what you are trying to accomplish instead of a pseudo question. Commented Dec 7, 2010 at 17:05

3 Answers 3

15

You can't. That's not the way return works. It exits only from the current function.

Being able to return from a function further up the call stack would break the encapsulation offered by the function (i.e. it shouldn't need to know where it's being called from, and it should be up to the caller to decide what to do if the function fails). Part of the point of a function is that the caller doesn't need to know how the function is implemented.

What you probably want is something like this:

function hello1() {
    function hello2() {
        if (condition) {
            return false;
        }
        return true;
    }

    if (!hello2()) {
        return;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

You shouldn't use inner-functions to control program flow. The ability to have inner-functions promotes scoping context and accessibility.

If your outer-function relies on its inner-function for some logic, just use its return value to proceed accordingly.

Comments

2

jumping up the stack like that is probably a bad idea. you could do it with an exception. we control execution flow like that in one spot at work, because its a straightforward workaround for some poorly designed code.

1 Comment

Even with exceptions, it's up to one of the functions higher up in the call stack to handle it. That would require every function call to hello1 to be wrapped in a try...catch block... kinda messy ;-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.