Stopping a JavaScript function when a certain condition is met
379,688
Solution 1
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.
Solution 2
use return
for this
if(i==1) {
return; //stop the execution of function
}
//keep on going
Solution 3
The return
statement exits a function from anywhere within the function:
function something(x)
{
if (x >= 10)
// this leaves the function if x is at least 10.
return;
// this message displays only if x is less than 10.
alert ("x is less than 10!");
}
Solution 4
Use a try...catch
statement in your main function and whenever you want to stop the function just use:
throw new Error("Stopping the function!");
Related videos on Youtube
Author by
Rhys
Updated on July 05, 2022Comments
-
Rhys over 1 year
I can't find a recommended way to stop a function part way when a given condition is met. Should I use something like
exit
orbreak
?I am currently using this:
if ( x >= 10 ) { return; } // other conditions;
-
g.d.d.c over 13 yearsReturning false only makes sense if you're expecting a boolean return and will return true in other situations. He might return an array value, or a status indicator, or a hint as to how far through the function he made it as the result of the conditional.
-
Rhys over 13 yearsThanks for the confirmation. Couldn't find this answer by Googling.
-
g.d.d.c over 9 years@Wolle - you'll notice I both listed it as an alternative and with the caveat that calls to the function would need to be wrapped in a try / catch block. Depending on the function, the project scope, and what the function accomplishes, raising an exception to exit might be perfectly appropriate. One can't know without in depth knowledge of the OP's implementation. Either way, my answer was to use
return
, notthrow
. -
Intervalia about 6 yearsThrowing an exception to exit is a very viable option. For example, calling a function without a valid variable will throw an
ReferenceError
exception. I have setter functions in classes that can only take values from0
to100
and if the value is outside of that range I throw aRangeError
exception. Exceptions are meant to stop flow when something happened that the function was not expecting. An exception to the rules. -
Fabian von Ellerts almost 5 yearsGreat, but please only use this if you stop the function due to an actual error or missing parameter and use
return
otherwise. -
harry over 2 yearsI found this when i was messing around with my code. Also you don't need to say script before it you can say anything but i like to say script because it makes sense.
-
loakesh bachhu almost 2 yearsthrowing an Error inside a try and catch will work if you want to terminate the whole function