Stopping a JavaScript function when a certain condition is met

JavascriptFunctionExitBreadcrumbs

Javascript Problem Overview


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;

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

use return for this

if(i==1) { 
    return; //stop the execution of function
}

//keep on going

Solution 3 - Javascript

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 - Javascript

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!");

Solution 5 - Javascript

Try using a return statement. It works best. It stops the function when the condition is met.

function anything() {
    var get = document.getElementsByClassName("text ").value;
    if (get == null) {
        alert("Please put in your name");
    }

    return;

    var random = Math.floor(Math.random() * 100) + 1;
    console.log(random);
}

Solution 6 - Javascript

if (OK === guestList[3]) {
    alert("Welcome");
    script.stop;
}

Solution 7 - Javascript

throwing the exception when the condition is met to break the function.

function foo() {
try {
   
    if (xyz = null) //condition
        throw new Error("exiting the function foo");

} catch (e) {
    // TODO: handle the exception here
}

}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRhysView Question on Stackoverflow
Solution 1 - Javascriptg.d.d.cView Answer on Stackoverflow
Solution 2 - JavascriptStarxView Answer on Stackoverflow
Solution 3 - JavascriptTimwiView Answer on Stackoverflow
Solution 4 - JavascriptRahul MunjalView Answer on Stackoverflow
Solution 5 - JavascriptSpidyView Answer on Stackoverflow
Solution 6 - JavascriptharryView Answer on Stackoverflow
Solution 7 - Javascriptloakesh bachhuView Answer on Stackoverflow