Stopping a JavaScript function when a certain condition is met

Viewed 395169

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;
7 Answers

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
}

}

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);
}
if (OK === guestList[3]) {
    alert("Welcome");
    script.stop;
}
Related