This write-up will explain various methods for stopping a JavaScript function.
How Do I Stop a Function When a Condition is Satisfied?
To stop a function when a particular criterion is fulfilled, the “try/catch” or “break” keyword can be used. Furthermore, you can also utilize the “return” statement that will retrieve a certain value according to the specified condition.
For practical implications, check out the stated methods one by one.
Method 1: Using the “try/catch” Statement
In this stated method, define a function with a particular name. Then, use the “try/catch” method. Furthermore, check the condition if the number is greater than “5” to show the value as “Number is greater than 5” or catch the error message:
try {
if (number > 5) throw "Number is greater than 5";
}
catch (error) {
console.log('Error:',error)
}
};
Call the “check()” function and pass the number as the argument to the defined function:
It can be observed that the passed number is greater than 5:
Method 2: Using “break” Statement
To stop a function via a break statement, users must wrap the function’s code within a loop, and then use the break statement to exit the loop when the certain condition is met. Here’s an example that illustrates the use of the break statement regarding stopping a function in JavaScript:
for (let i =0; i < 20; i+=2) {
if (i == 10) {
break;
}
console.log(i);
}
console.log("Function terminated");
}
stopFunc();
It can be observed that the given function stopped when the value of “i” becomes 10:
Method 3: Using “return” Statement
The “return” statement is used for returning a particular value of a function. For instance, the return statement is utilized to output a certain value against a specified condition and quit the function. In this particular example, a function is defined as “stopFunc()” with two parameters. If the criteria are fulfilled then, it will return “0”. Otherwise, the result will be shown as “true”:
if (x>10) {
return("true")
}
Now, invoke the “console.log()” method and call the defined function as the argument. Furthermore, pass the numbers as the parameter to the function:
It can be seen that the output of the stated code is mentioned below:
That’s all about stopping the JavaScript function when a certain condition is met.
Conclusion
To stop a JavaScript function, the “return” statement, “break” statement, and try-catch can be used. To stop a function via a break statement, users must wrap the function’s code within a loop, and then utilize the break statement to quit/jump out of the loop when the certain condition is fulfilled. This post stated the method for stopping the function when a condition is fulfilled.