How can I use return in javascript
function hello1() {
function hello2() {
if (condition) {
return; // How can I exit from hello1 function not hello2 ?
}
}
}
How can I use return in javascript
function hello1() {
function hello2() {
if (condition) {
return; // How can I exit from hello1 function not hello2 ?
}
}
}
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;
}
}
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.
hello1 to be wrapped in a try...catch block... kinda messy ;-)