Break execution from function - javascript

Is possible to break execution program from function or I need to check boolean val returned?
Code
function check(something) {
if (!something) return;
// Else pass and program continuing
}
check(false); // I want to stop execution because function has returned
// Or I need to check value like if (!check(false)) return; ?
// I want easiest possible without re-check value of function..
alert("hello");

One way would be to through an Error, but otherwise you would need to use a boolean check, yes. I would recommend to use the boolean
function check(something) {
if (!something) throw "";
// Else pass and program continuing
}
check(false); // I want to stop execution because function has returned
// Or I need to check value like if (!check(false)) return; ?
// I want easiest possible without re-check value of function..
alert("hello");

Easiest...
(function(){
function check(something) {
if (!something) return false;
// Else pass and program continuing
}
if(!check(false)) return;
alert("hello");
});
(function(){ ... }); is called IIFE Immediately-invoked function expression.

Put your code in an IIFE, then you can use return
(function() {
function check(something) {
if (!something) {
return false;
} else {
return true;
}
}
if (!check(false)) {
return;
}
alert("hello");
});

Related

the if statement is not running and returning the string [duplicate]

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:-)

Check if function returns true to execute another function

I have written a form validation using JS which ends with return(true);
function check() {
....validation code
return(true);
}
All I want is, need to check if check() function returns true, I want to execute another function.
Code I have tried is as follows:
if(check() === true) {
function() {
//Another function code
}
}
You should use return true; and your if statement doesn't need the === true comparison.
function check() {
//validation code
return true;
}
if(check()) {
//Another function code
}
JSFIDDLE
First of all, return is not a function, you can just do this:
return true;
Now, to only execute myFunction if check returns true, you can do this:
check() && myFunction()
This is shorthand for:
if(check()){
myFunction();
}
You don't need to compare the return value of check with true. It's already an boolean.
Now, instead of myFunction(), you can have any JavaScript code in that if statement. If you actually want to use, for example, myFunction, you have to make sure you've defined it somewhere, first:
function myFunction() {
// Do stuff...
}
You just need to modify your first code snippet. return is a keyword, what you are trying to do is to execute it as a function.
function check() {
....validation code
return true;
}
You'll need to change your 2nd snippet slightly, to execute the function too however... The simplest way is to wrap it as an anonymous function using curly braces:
if(check()) {
(function() {
//Another function code
})();
}
You're not calling the function in your affirmative clause, only declaring it. To call an anonymous function do this:
(function (){...})()
You could type
$this.myFunction=function(){
//code here
}
and to execute some code if a the myFunction function is true, you could use booleans
such as e.g.
if(//your function is true){
and so on

javascript confirm function ok and cancel returns same result

Here in result() method, whenever it comes to else part, I need to get out of the function callthis().
It should not execute kumar() function.
Is this possible?
Actually, I can use like this
if(result) //if this method is true, it will come inside
{
kumar();
}
But this is not I want. while returning false from result() method, it should get out of the loop function calthis()
function calthis()
{
var i=1;
if(i==0)
{
alert("inside if");
}
else
{
alert("inside else");
result();
kumar();
}
}
function result()
{
var res = confirm("are you wish to continue");
if(res==true)
{
return true;
alert("inside if result");
}
else
{
return false;
}
}
function kumar()
{
alert("inside kumar");
}
Click here
There's a bunch wrong here.
First, if (result) just tests whether the variable result contains a truthy value, it doesn't actually invoke the function. If you want to test the return value of the function, you need
if (result()) {
Secondly, you're not understanding that return immediately leaves the current function. You can't meaningfully do this:
if(res==true)
{
return true;
alert("inside if result");
}
That alert cannot be reached. The function returns immediately when return true is encountered.
Thirdly, to exit callThis early, you simply need to return early. It's up to the function callThis to conditionally return; you cannot force a return from down inside the result function. A function cannot forcibly return out if the context that called it. It's not up to the internals of the result function to determine if kumar should run. You cannot influence the path of execution in the calling method directly. All result can do is return something, or (needlessly complex in this case) accept a callback and conditionally execute it.
Just return from callThis if the result of result() is false:
function calthis()
{
var i=1;
if(i==0)
{
alert("inside if");
}
else
{
alert("inside else");
if (!result()) return;
kumar();
}
}
To exit any function simply use return;
However it seems like you want to call a function if the user clicks confirm, is that correct? If so:
var res = confirm("are you wish to continue");
if (res === true)
{
kumar();
}
If you want to call a function if the user does not click confirm:
var res = confirm("are you wish to continue");
if (!res)
{
kumar();
}
You got a lot of confusing code going on there, but if the idea is to stop a function, simply use "return false;" and the code execution stops

return true, breaks code in javascript

Having the following code:
function test(x) {
if(x=='a') return false;
return true;
}
if(y ==x) {
return test('a');
group['ids']= inputs.val();
console.log(group);
}
why return true simply breaks my code by not continuing beyond the return?
Note: I want the return test()'s answer to control if either it should continue with the code OR not
Update
I already do something like:
var response = test('b');
if (response==false) return false;
... more code here ...
But I want to avoid having to do so on every invoke of that function
Because that's what return does in almost every programming language: it
exits the function and
returns a value
If you need other code to be executed, put it before the return statement.
Edit: I saw your edit, but it doesn't change the very nature of return in that (and every) context. It will continue to stop the flow of the current scope, returning to the nearest higher scope with a value (in your case, true or false).
The keyword return, as it name suggests, returns the program flow control to the calling function and optionally sets the function's return value.
This works the same way in every C-like language.
What you probably wanted to do is a Delphi-like approach, where the keyword Result works differently - it just sets the return value that will be used when the function terminates, but does not immediately terminate the function.
function() {
var result = someDefaultValue;
if (someCondition)
result = otherValue;
if (otherCondition)
result = yetAnotherValue;
return result;
}
try putting return at the end because return true will break the execution and nothing will execute after that
When a return statement executes, the execution of the current function ends, and control of the program is returned to the context that invoked the function. Anything after a return statement will not be executed.
The return keyword causes a function to end ('return') when the interpreter reaches that keyword and does not continue to process anything after the return statement (in that same function).
You could rewrite what you have:
group['ids']= inputs.val();
console.log(group);
return true;
I typically find out which scenarios are bad/errors and return false; out of them, THEN continue on to the code which is correct.
function Testmcdooder (test) {
if (test === false) {
// just exit up here
return false;
}
// now all of this code will run only if we're fine
group['ids']= inputs.val();
console.log(group);
}
The return statement exists from the function. I think that you rather want an if statement:
if (y == x) {
if (test('a')) {
group['ids']= inputs.val();
console.log(group);
}
}
If you also want to return the value after determining if the other statemens should run:
if (y == x) {
if (test('a')) {
group['ids']= inputs.val();
console.log(group);
return true;
} else {
return false;
}
}
Alternatively:
if (y == x) {
var cond = test('a');
if (cond) {
group['ids']= inputs.val();
console.log(group);
}
return cond;
}

Early exit from function?

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:-)

Categories

Resources