Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use return in javascript

How can I use return in javascript

function hello1() {

    function hello2() {

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

    }

}
like image 467
faressoft Avatar asked Dec 07 '10 16:12

faressoft


People also ask

Can we use return in JavaScript?

When a return statement is used in a function body, the execution of the function is stopped. If specified, a given value is returned to the function caller. For example, the following function returns the square of its argument, x , where x is a number.

What is return used for in JavaScript?

The return statement stops the execution of a function and returns a value.

How do you add a return in JavaScript?

The newline character is \n in JavaScript and many other languages. All you need to do is add \n character whenever you require a line break to add a new line to a string.

How do you call a return function in JavaScript?

Putting the parenthesis at the end of a function name, calls the function, returning the functions return value.


3 Answers

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;
    }
}
like image 133
Cameron Avatar answered Oct 03 '22 01:10

Cameron


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.

like image 23
Luca Matteis Avatar answered Oct 03 '22 02:10

Luca Matteis


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.

like image 31
Dustin Getz Avatar answered Oct 03 '22 02:10

Dustin Getz