Returning true/false after multiple functions - javascript

function topFunction() {
if (checkUserRole()) {
//trying to figure out if I will hit this line
}
}
checkUserRole() {
anotherFunction()
}
anotherFunction() {
return true;
}
So what I am asking is, will that original checkUserRole() be considered true in this scenario? Or do I somehow need to pass the true up from anotherFunction() to checkUserRole()?

No, you will need to explicitly return it up:
function topFunction() {
if (checkUserRole()) {
//trying to figure out if I will hit this line
}
}
checkUserRole() {
return anotherFunction();
}
anotherFunction() {
return true;
}
Without the return in the checkUserRole function the true that comes back from anotherFunction gets lost. The way you had originally written it returns nothing from checkUserRole, which means that it will fail the "truthy" test in the if statement in topFunction no matter what happens in either anotherFunction or checkUserRole.

You're missing the return statement inside the checkUserRole method

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

how to avoid repeating return false line

On many functions I have this line:
if (!$('.postitle').hasClass('pmarked')) {return false;}
To avoid repeating it so often I tried this:
function falsea(){
if (!$('.postitle').hasClass('pmarked')) {return false;}
}
and then call the above - falsea() instead of if (!$('.postitle')...
It doesn't work.
Is there any simillar way to avoid repeating entire line each time ?
The level is incorrect.
return false actually do nothing but stop your function for further running.
If you are not outputing any result, this is just same as simply write return.
So in your falsea() function, your return false stop the function, not the outer one but the falsea() itself, it won't make the mother do anything.
What you can do is
function falsea(){
return $('.postitle').hasClass('pmarked'))
}
In mother,
if (!falsea()) return
It doesn't work.
It doesn't work because that's not how functions work (in any language, really). A return statement in the callee doesn't cause the caller to terminate. Simple example:
function foo() {
console.log('before bar()');
bar();
console.log('after bar()');
}
function bar() {
console.log('in bar; before return');
return false;
console.log('in bar; after return');
}
foo();
What you can do is put the condition in its own function to reuse that, but you still need an if statement in every caller:
function hasPmarked(){
return $('.postitle').hasClass('pmarked');
}
// in caller
if (!hasPmarked()) {
return false;
}
Is there any simillar way to avoid repeating entire line each time ?
You could create a function that accepts a callback and only executes the callback if the check succeeds.
For example:
function doStuffIfPMarked(stuff) {
if ($('.postitle').hasClass('pmarked')) {
stuff();
}
}
Then the caller can do:
doStuffIfPMarked(function() {
// do something
});
I.e. if you had this before:
function foo() {
if (!$('.postitle').hasClass('pmarked')) {return false;}
// do my stuff
}
you would write
function foo() {
doStuffIfPMarked(function() {
// do my stuff
});
}
You still need to repeat some code, but you are abstracting the condition logic away.
Your function will only return false or undefined.
Try adding at the end
return true;
Or even simpler, just do:
return !$('.postitle').hasClass('pmarked')
Keep in mind that the return doesn't propogate so you will still need check the return value of this function and return.
if (falsea()) {return false;}

Break execution from function

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

return false doesnt seem to work in this javascript function

I have a onclick function,
$("#mymodal").on("click",".close",function() {
checkpincode();
checkzipcode();
});
and fn checkpincode returns false but the execution still continues and my checkzipcode function gets executed. Any ideas why this behavior??
you need
$("#mymodal").on("click",".close",function() {
if(!checkpincode()){
return false;
}
checkzipcode();
});
or
$("#mymodal").on("click",".close",function() {
checkpincode() && checkzipcode()
});
The return value from checkpincode() is passed to calling statement in click handler and does not mean it will cause return of function from which checkpincode() is invoked. You can use if statement to conditionally execute the checkzipcode() function.
$("#mymodal").on("click",".close",function() {
if(checkpincode())
checkzipcode();
});
For more understand you can assign value returned form checkpincode() and use it for calling checkzipcode();
$("#mymodal").on("click",".close",function() {
result = checkpincode();
if(result)
checkzipcode();
//return result; //if you want.
});

use several JS function on form check

i have a select box to allow the user select what kind of form he need to fill in.
the 2 options are for a single person or someone from a group therefore some of the fieldsets that are in use in the single are switched with some from the group ones.
so for the single user i have this functions: singleinformation, winninginformation, reporterinformation, parentalinformation.
and for the group i have groupinformation, winninginformation, reporterinformation.
in the onsubmit i have another check() function that will check the check box and by the selection will call the right functions
function Check() {
if (document.getElementById("type").value=="s") {
return CheckSingleInformation();
return CheckWinningInformation();
}
else if (document.getElementById("type").value=="g") {
return CheckGroupInformation();
return CheckWinningInformation();
}
}
for some reason, after finishing the first function, if it returned without false it will send the form and not stop at the first error of the second function
what can i do to fix it?
onsubmit must have as value "return Check()". If you simply call Check(), returning values won't be used and it will continue with the submission.
never mind... found the answer :-)
first i have changed the main function to look like this:
function Check() {
if (document.getElementById("type").value=="s") {
CheckSingleInformation();
CheckWinningInformation();
}
else if (document.getElementById("type").value=="g") {
CheckGroupInformation();
CheckWinningInformation();
}
}
but then i found out it wont stop after the first function so i changed it to be like this
function Check() {
if (document.getElementById("type").value=="s") {
if (CheckSingleInformation()==false) {return false}
if (CheckWinningInformation()==false) {return false}
}
else if (document.getElementById("type").value=="g") {
if (CheckGroupInformation()==false) {return false}
if (CheckWinningInformation()==false) {return false}
}
}
is that the right way?
2 notes:
Returning "true" from the onsubmit() event will stop it from propagating; the form won't be submitted (usually is the behaviour you want when you're doing an AJAX posting)
checkWinningInformation(); will never be called in both blocks, since the statement prior to it is a "return" which actually jumps out of the method execution... that can't be what you want, can it?
Check nested conditions,
function Check() {
if (document.getElementById("type").value=="s") {
if(!CheckSingleInformation()){
return CheckWinningInformation();
}
return true;
}
else if (document.getElementById("type").value=="g") {
if(!CheckGroupInformation()){
return CheckWinningInformation();
}
return true;
}
}
Return is used in a function for two reasons:
You want the script to stop executing if something happens.
You want the function to return a value to the calling function.
You used return like so:
return CheckSingleInformation(); <-- exit here
return CheckWinningInformation();
Your script will "exit" (or submit the form) right after the first return!
What you could do to resolve this: Call CheckWinningInformation() at the end of CheckSingleInformation() as well as at the end of CheckGroupInformation().
Using logical AND operator (&&) would be fine.
so the following code :
function Check() {
if (document.getElementById("type").value=="s") {
return CheckSingleInformation();
return CheckWinningInformation();
}
else if (document.getElementById("type").value=="g") {
return CheckGroupInformation();
return CheckWinningInformation();
}
}
could be :
function Check() {
if (document.getElementById("type").value=="s") {
return (CheckWinningInformation() && CheckSingleInformation());
}
else if (document.getElementById("type").value=="g") {
return (CheckWinningInformation() && CheckGroupInformation());
}
}

Categories

Resources