Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stopping a JavaScript function when a certain condition is met

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 or break?

I am currently using this:

if ( x >= 10 ) { return; }   // other conditions; 
like image 420
Rhys Avatar asked Aug 21 '10 02:08

Rhys


People also ask

How do you stop a function from working in JavaScript?

To stop the execution of a function in JavaScript, use the clearTimeout() method. This function call clears any timer set by the setTimeout() functions.

Can you break out of a function JavaScript?

Using break to exit from functions in javascript is a less traditional way compared to using return. Break is mostly used to exit from loops but can also be used to exit from functions by using labels within the function.


1 Answers

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.

like image 195
g.d.d.c Avatar answered Oct 13 '22 08:10

g.d.d.c