ding van ding van - 3 months ago 20
AngularJS Question

How to exit in the middle of a function?

How about nested if?

$scope.addToCart = function () {
if (flagA) {
if (flagB) {
if (flagC) {
alert('nononono!');
return;
}
}
}
someAnotherFunction();
};





I have a function:

$scope.addToCart = function () {
var foo = 5;
if (someFlag == 'Y') {
alert('warning!');
return;
}
someAnotherFunction();
};


I invoke this function somewhere

ng-click = "addToCart()"


My intention is to exit this function if

someFlag == 'Y'


then not to execute

someAnotherFunction();


But it still execute it.

WebStorm tell me this
return
is unnecessary so it could be safely removed.

Answer

If you are sure that the if condition is satisfied, but return isn't working, then you can also try putting someAnotherFunction(); into else:

if (someFlag == 'Y') {
    alert('warning!');
    return;
}
else {
    someAnotherFunction();
}

That way someAnotherFunction() can be executed only if the if block isn't.

Addendum

The original code should work and this is just a workaround, as pointed out in the comment. However both methods achieve the same goal in theory.

For more details, check this question - for details on the differences.