Say I have a function:
function foo(){
// do a bunch of stuff, manipulate DOM, etc.
// and then:
if(some_condition) return true;
else return false;
}
Since it would be nice to both execute the function’s “bunch of stuff” AND use its return value at the same moment, I’m wondering if it’s right to do this:
if( foo() ){ // foo happens right here
// do some stuff because foo returned true
}
Is this correct syntax and usage?
This is absolutely fine. Even if
foodoesn’t return a boolean value, the return will be forced boolean, so in any case it is fine to do this.What your’re doing is just not substituting a variable for the return value of
foo().The only time this would be a problem is if
foo()return different values, in which case if you want the value to be the same throughout your code, you have to set the return value to a variable and use that variable instead.BTW, this is one of the basics of javascript. Unless you’re just starting, you should know this already.
Oh, and as people have said in the comments, this is not using a function as a parameter.
Using a function as a parameter would be doing this: