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;
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.
use return for this
if(i==1) {
return; //stop the execution of function
}
//keep on going
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!");
}
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!");
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
I have a function:
function myfunction() {
if (a == 'stop') // How can I stop the function here?
}
Is there something like exit() in JavaScript?
You can just use return.
function myfunction() {
if(a == 'stop')
return;
}
This will send a return value of undefined to whatever called the function.
var x = myfunction();
console.log( x ); // console shows undefined
Of course, you can specify a different return value. Whatever value is returned will be logged to the console using the above example.
return false;
return true;
return "some string";
return 12345;
Apparently you can do this:
function myFunction() {myFunction:{
console.log('i get executed');
break myFunction;
console.log('i do not get executed');
}}
See block scopes through the use of a label: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label
I can't see any downsides yet. But it doesn't seem like a common use.
Derived this answer: JavaScript equivalent of PHP’s die
function myfunction() {
if(a == 'stop')
return false;
}
return false; is much better than just return;
This:
function myfunction()
{
if (a == 'stop') // How can I stop working of function here?
{
return;
}
}
Using a little different approach, you can use try catch, with throw statement.
function name() {
try {
...
//get out of here
if (a == 'stop')
throw "exit";
...
} catch (e) {
// TODO: handle exception
}
}
if you are looking for a script to avoid submitting form when some errors found, this method should work
function verifyData(){
if (document.MyForm.FormInput.value.length == "") {
alert("Write something!");
}
else {
document.MyForm.submit();
}
}
change the Submit Button type to "button"
<input value="Save" type="button" onClick="verifyData()">
hope this help.
Using a return will stop the function and return undefined, or the value that you specify with the return command.
function myfunction(){
if(a=="stop"){
//return undefined;
return; /** Or return "Hello" or any other value */
}
}
I think throw a new error is good approach to stop execution rather than just return or return false. For ex. I am validating a number of files that I only allow max five files for upload in separate function.
validateMaxNumber: function(length) {
if (5 >= length) {
// Continue execution
}
// Flash error message and stop execution
// Can't stop execution by return or return false statement;
let message = "No more than " + this.maxNumber + " File is allowed";
throw new Error(message);
}
But I am calling this function from main flow function as
handleFilesUpload() {
let files = document.getElementById("myFile").files;
this.validateMaxNumber(files.length);
}
In the above example I can't stop execution unless I throw new Error.Just return or return false only works if you are in main function of execution otherwise it doesn't work.
I dislike answering things that aren't a real solution...
...but when I encountered this same problem, I made below workaround:
function doThis() {
var err=0
if (cond1) { alert('ret1'); err=1; }
if (cond2) { alert('ret2'); err=1; }
if (cond3) { alert('ret3'); err=1; }
if (err < 1) {
// do the rest (or have it skipped)
}
}
Hope it can be useful for anyone.
If you are using jquery. This should stop the function from bubbling up to so the parent function calling this should stop as well.
function myfunction(e)
{
e.stopImmediatePropagation();
................
}
exit(); can be use to go for the next validation.
type any random command that throws an error, for example:
exit
or
die:-)
What is the difference between using return in outside of else condition and inside of else condition?
I know the best code is without use else and I know both are doing similarly same. Is there difference or advantages?
function f1() {
if (1 == 1) {
return true;
} else {
return false;
}
}
function f2() {
if (1 !== 1) {
return true;
} else {
return false;
}
return false
}
console.log(f1());
console.log(f2());
Not related to your previous question, but only this:
In Method:2, the last return statement (ie return true;) is virtually useless. Because last line in the SaveVersionMainScreen() won't be executed as there is if and else both conditions are present. Which should account for all cases.
if you have if statement within block code and contains return in both if and else block. Its mean either if block will execute and return from method or else block will execute and return. Other statements below that blocks will not execute and compiler may give you error something like
Statements cannot be reached
For Example:
SaveVersionMainScreen() {
let element = this.commonValidation(true);
if (element) {
return false;
}
else{
return true;
}
// Below statements will never run
var a=2;
var b=3;
var c=4;
return true;
}
Way to go changing you question completely. Leaving my answer anyway for now.
Your version 2 is bad practice, code would not work in a strict language like Java as you have a return statement that cannot be reached. As for your test removing the else from your function should solve it for you, but the issueseems to be with the test and not your code.
SaveVersionMainScreen() {
let element = this.commonValidation(true);
if (element) {
return false;
}
return true;
}
I'm trying to write a function that checks if a number "N" is even or odd by subtracting 2 until it gets to 1 or 0. A final value of 0 represents even. The goal here is to use a recursive function to reach the final result, but I'm having some issues where all I have returned are undefined.
This is what I have so far.
function isEven(number) {
function subTwo(number) {
if (number == 0) {
return true;
}
else if (number == 1) {
return false;
}
else if (number > 0) {
number -= 2;
subTwo();
}
else {
console.log("bruh");
}
};
};
console.log(isEven(50));
// → true
console.log(isEven(75));
// → false
console.log(isEven(-1));
// → ??
Does anyone see what I'm doing wrong or have any advice for me?
Thanks.
EDIT:
Thanks for the help guys. It was suggested that I remove subTwo completely and use isEven as the recursive function, and that I had to use return isEven(number) within the second if/else statement.
Both of those suggestions together helped the code compile correctly.
Thanks a ton guys, although I'm not sure why I got downvoted lol.
Your problem is here:
subTwo();
You need to pass the current version of number into it: subTwo(number); and return it.
you could also fix the problem by omitting the parameter in the internal function, like so: function subTwo(){...} The internal function already has access to the parent function's parameter (closure), so you don't need to pass that into the internal one.
also, this is not returning anything, it's just logging. JavaScript always returns something. If you don't say return "something", it returns undefined.
else {
console.log("bruh");
}
Personally, I would also rework you code like so:
function subTwo(number) {
if (number > 0) {
number -= 2;
subTwo();
}
else if (number == 1) {
return false;
}
else if (number == 0) {
return true;
}
else {
console.log("bruh");
}
};
The statements are then in descending order, so you can quickly see the progression. It helps people look and see if anything has been missed.
The problem is that you define the function subTwo but it's never actually called when isEven is called. A simpler version would be to not even have another function and do it all with recursive calls of isEven
function isEven(number) {
if (number === 0) {
return true;
} else if (number === 1) {
return false;
} else {
return isEven(number - 2)
}
}
EDIT
Alternatively, if you really want the additional function, notice that you defined subTwo to take in a parameter but you did not pass in the parameter when recursively calling it via subTwo();. Also, when you recursively call subTwo(number), make sure you actually have return subTwo(number) so the value is returned at each recursive call. Additionally, you need to actually call the function and return the result when isEven(number) is called via a return statement and wrapping the function in brackets and calling it with number or manually calling it using return subTwo(number). See below for an example of how you would return at each stage so it passes it all the back up to the original call of isEven(number):
function isEven(number) {
return (function subTwo(number) {
if (number === 0) {
return true;
}
else if (number === 1) {
return false;
}
else if (number > 0) {
number -= 2;
return subTwo(number);
}
else {
console.log("bruh");
}
})(number);
};
As was said in the comments you never check for a value less than 0. What happens is when you enter the value -1 is it jumps down to the else part of your code. The part that says "console.log("bruh");" After completing that line the program keeps going and returns... nothing. You dont return anything, hence why you get undefined. You should set up your code to handle the case when a negative number is passed in.
Let's say I have this code:
var myVar = 0;
function myFunctionOne() {
myVar = myVar + 2;
if(myVar <= 3) {
alert("all is good");
} else {
showError(myVar);
}
}
function myFunctionTwo() {
myVar = myVar + 2;
if(myVar <= 3) {
alert("all is good");
} else {
showError(myVar);
}
}
function myFunctionThree() {
//This should never run....
myVar = myVar + 2;
if(myVar <= 3) {
alert("all is good");
} else {
showError(myVar);
}
}
function showError(myVar) {
alert("Error Var is larger than 3. Var is" + myVar);
return false;
//This doesn't seem to stop anything
}
myFunctionOne();
myFunctionTwo();
myFunctionThree();
Here is also the fiddle: http://jsfiddle.net/dzjk44Lr/
What can I put inside my showError() function, that will kill any subsequent function calls? In this example, myFunctionThree(); should never run.
I know this is a simple example, but I'm trying to get my head around the module pattern, and in my module I have a lot of functions that delegate work, and modify variables. So if one function fails, or is given an illegal variable, I want everything to stop and show the user an error. Because if there was an error in myFunctionOne() for example, there is no point in continuing to execute any of the other code.
I guess, I'm looking for something like the php exit() function.
Any advice about how to do this, or how I should do it differently would be greatly appreciated.
You can throw an error:
throw new Error("Error Var is larger than 3. Var is" + myVar);
You can use javascript throw statement.
According to Mozilla MDN
Execution of the current function will stop (the statements after throw won't be executed), and control will be passed to the first catch block in the call stack. If no catch block exists among caller functions, the program will terminate.
Example:
throw "An error ocurred."
You can also go pro and throw an error object like this:
throw new MyAppError("custom error str", 128);
I have a function:
function myfunction() {
if (a == 'stop') // How can I stop the function here?
}
Is there something like exit() in JavaScript?
You can just use return.
function myfunction() {
if(a == 'stop')
return;
}
This will send a return value of undefined to whatever called the function.
var x = myfunction();
console.log( x ); // console shows undefined
Of course, you can specify a different return value. Whatever value is returned will be logged to the console using the above example.
return false;
return true;
return "some string";
return 12345;
Apparently you can do this:
function myFunction() {myFunction:{
console.log('i get executed');
break myFunction;
console.log('i do not get executed');
}}
See block scopes through the use of a label: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label
I can't see any downsides yet. But it doesn't seem like a common use.
Derived this answer: JavaScript equivalent of PHP’s die
function myfunction() {
if(a == 'stop')
return false;
}
return false; is much better than just return;
This:
function myfunction()
{
if (a == 'stop') // How can I stop working of function here?
{
return;
}
}
Using a little different approach, you can use try catch, with throw statement.
function name() {
try {
...
//get out of here
if (a == 'stop')
throw "exit";
...
} catch (e) {
// TODO: handle exception
}
}
if you are looking for a script to avoid submitting form when some errors found, this method should work
function verifyData(){
if (document.MyForm.FormInput.value.length == "") {
alert("Write something!");
}
else {
document.MyForm.submit();
}
}
change the Submit Button type to "button"
<input value="Save" type="button" onClick="verifyData()">
hope this help.
Using a return will stop the function and return undefined, or the value that you specify with the return command.
function myfunction(){
if(a=="stop"){
//return undefined;
return; /** Or return "Hello" or any other value */
}
}
I think throw a new error is good approach to stop execution rather than just return or return false. For ex. I am validating a number of files that I only allow max five files for upload in separate function.
validateMaxNumber: function(length) {
if (5 >= length) {
// Continue execution
}
// Flash error message and stop execution
// Can't stop execution by return or return false statement;
let message = "No more than " + this.maxNumber + " File is allowed";
throw new Error(message);
}
But I am calling this function from main flow function as
handleFilesUpload() {
let files = document.getElementById("myFile").files;
this.validateMaxNumber(files.length);
}
In the above example I can't stop execution unless I throw new Error.Just return or return false only works if you are in main function of execution otherwise it doesn't work.
I dislike answering things that aren't a real solution...
...but when I encountered this same problem, I made below workaround:
function doThis() {
var err=0
if (cond1) { alert('ret1'); err=1; }
if (cond2) { alert('ret2'); err=1; }
if (cond3) { alert('ret3'); err=1; }
if (err < 1) {
// do the rest (or have it skipped)
}
}
Hope it can be useful for anyone.
If you are using jquery. This should stop the function from bubbling up to so the parent function calling this should stop as well.
function myfunction(e)
{
e.stopImmediatePropagation();
................
}
exit(); can be use to go for the next validation.
type any random command that throws an error, for example:
exit
or
die:-)