how to avoid repeating return false line - javascript

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

Related

Stop subsequent methods call of onclick

If this is problem already existed then please help me mark it as duplicate cause I cannot find the similar solution.
While having multiple methods call on onclick attribute, for example:
<a onclick="foo();afterFoo();afterAfterFoo();"/>
I want to stop subsequent calls like afterFoo() , afterAfterFoo(); when foo() meets some condition.
I tried return false; in method foo() but it still calls other methods. I remember this trick used to work as expected.
It doesn't happen that way. You need to create a wrapping function and attach it as onClick handler rather than call the 3 functions from it directly. You may call your 3 functions from the wrapping function based on the if conditions.
<a onclick="clickHandler();"/>
function clickHandler() {
foo() && afterFoo() && afterAfterFoo();
}
You can do it simply by using ifconditions:
function foo() {
console.log('foo')
return true;
}
function afterFoo() {
console.log('afterFoo')
return false;
}
function afterAfterFoo() {
console.log('afterAfterFoo')
return true;
}
function specialSequence() {
if (foo())
if (afterFoo())
afterAfterFoo();
}
<a onclick="specialSequence();">Click Me</a>
So what happens here:
we are calling specialSequence. It runs foo and if it returns true, we continue to the next sequence function afterFoo, and if this returns true we continue to afterAfterFoo. But it returns false, which means that after running afterFoo the function specialSequence will stop running.
After you stated that there are several parameters to each function and you don't want specialSequence to have the sum of parameters of all the functions its using, You can just use it in the html like this (simply copy the function to the onClick)
function foo() {
console.log('foo')
return true;
}
function afterFoo() {
console.log('afterFoo')
return false;
}
function afterAfterFoo() {
console.log('afterAfterFoo')
return true;
}
<a onclick="if (foo())
if (afterFoo())
afterAfterFoo();">Click Me</a>

Passing A Function As Argument To A Function

function say(something) {
console.log(something);
}
function exec(func, arg) {
return func(arg);
}
exec(say, "Hi, there.");
Why does this code work? I feel like it shouldn't since what is in the second function should return
say(something) (arg) {
console.log(something) ;
}
It works as it does because when you write return func(arg);, the func(arg) bit executes the function. What is returned is then the result of executing func(arg).
However, you're right that say() doesn't actually return a value, it just logs to the console within that function. The output you're seeing is the result of that log command. If you logged the returned value instead you'd see undefined as the result.
But if you'd passed a different function to exec which did return a value, then you'd need the return in exec() for it to work properly.
P.S. I'm not sure if this is part of what you're asking, but the difference between that and when you wrote exec(say, "hi there"); is that in that code, say is a reference to the "say" function. At that moment it's treated like any other variable, just the same as if you passed in a number or a string, for example.
The difference is the (), which causes the function to be executed, rather than passed as a reference.
In the question you seem to imply that you'd expect the source code of the say() function to be displayed, but this is not what it does, and also is not possible anyway.
Function say returns undefined (default value if no return keyword is used), and therefore function exec also returns undefined.
Proof:
function say(something) {
console.log(something);
}
function exec(func, arg) {
var result = func(arg);
console.log(result);
return result;
}
var result2 = exec(say, "Hi, there.");
console.log(result2);
Maybe you are looking for a closure, where exec returns a function for getting arg for the first handed over function func.
function say(something) {
console.log(something);
}
function exec(func) {
return function (arg) {
return func(arg);
};
}
exec(say)("Hi, there.");

Returning true/false after multiple functions

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

iOS return values to the asynchronous javascript calls

Below shown is js code which makes call to the native functions in iOS and Android, this function is called from another js method.Since the js calls to this function is asynchronous.we could not return any values in iOS.but in Android we could return the values without any issue.In iOS control dosent wait until i get the response.Actually we are not suppose to modify this function call otherwise we can pass a callback method from the caller function.Please help me to solve this issue
VestaPhoneBridge.IsAvailable = function(featureName)
{
if(isAndroid()) {
if(typeof VestaJavascriptInterface !== 'undefined')
{
return VestaJavascriptInterface.isAvailable(featureName);
}
return false;
}
else {
bridge.callHandler('initiateIsAvailableFunction',featureName,function(response) {
return response;
})
}
};
I assume you're talking about this line.
bridge.callHandler('initiateIsAvailableFunction',featureName,function(response) {
return response;
})
The problem will most likely be your return. The anonymous function you are passing as a callback will be called whenever the async request is finished. This means that it will be called by something inside the callHandler code path.
Your function is then returning to that function, and not the VestaPhoneBridge.IsAvailable function. Your callback should set values, and perform changes instead of returning a value.
Example
function Foo(callback) {
callback(); // 42 is returned here, but not assigned to anything!
}
function Bar() {
var baz = Foo(function() {
// You want to return 42. But here you are in a totally different function
// scope! You are in the anonymous function's scope, not Bar, so you are not
// returning anything to the caller of Bar().
return 42;
}
alert(baz); // Foo doesn't return anything, so this is undefined!
}
alert(Bar()); // This is also undefined, nothing was returned.

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

Categories

Resources