Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to abort a jquery function with the condition of an if statement inside it returning false

Is it possible for me to abort the rest of a function depending on the condition of an if statement that's inside it without using an else condition?

Code example below.

("#btn").click(function(){
    if(name == call_name){
     alert(err)
    }

    //abort the rest of the function below without the need for else
});

Thank you.

like image 863
BaconJuice Avatar asked Feb 17 '23 09:02

BaconJuice


1 Answers

You can use a return statement to short-circuit a function.

("#btn").click(function(){
    if(name == call_name){
     alert(err)
     return false;
    }

    //abort the rest below without the need for else
});

Good point by others that in the case of an event like this you may want to return false to prevent the event bubbling and being caught by other handlers. In the general case though, return; works fine to short-circuit the function and tends to be the clearest way to do so.

like image 138
Ben McCormick Avatar answered Feb 18 '23 21:02

Ben McCormick