Stopping a JavaScript function when a certain condition is met

Rhys picture Rhys · Aug 21, 2010 · Viewed 324.4k times · Source

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;

Answer

g.d.d.c picture g.d.d.c · Aug 21, 2010

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.