How can I use return in javascript
function hello1() {
function hello2() {
if (condition) {
return; // How can I exit from hello1 function not hello2 ?
}
}
}
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.
The return statement stops the execution of a function and returns a value.
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.
Putting the parenthesis at the end of a function name, calls the function, returning the functions return value.
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;
}
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With