August 21, 2010

How to STOP a JavaScript function when a certain condition is met

Question by Rhys

I can’t find a recommended way to STOP a function part way thru when a given condition is met. Something like Exit, or Break?

I am currently using this?

If x >=10 {Return;}  
other conditions;

Answer by g.d.d.c

Return is how you exit out of a function body. You are using the correct approach.

I suppose, depending on how your application is structured, you could also use throw. That would typically require that your calls to your function are wrapped in a try / catch block.

Answer by Starx

use return for this

if(i==1) { 
    return; //stop the execution of function
}
else {
   //keep on going
}
...

Please fill the form - I will response as fast as I can!