Hopefully a quick question here.
Can you use a function's returned value in a if statement? I.e.
function queryThis(request) {
return false;
}
if(queryThis('foo') != false) { doThat(); }
Very simple and obvious I'm sure, but I'm running into a number of problems with syntax errors and I can't identify the problem.
Syntax. Use the IF function, one of the logical functions, to return one value if a condition is true and another value if it's false. For example: =IF(A2>B2,"Over Budget","OK")
Yes, you can use the nested usage of IF. Example: IF( Condition1, True,IF(Condition2,True).
A return statement is used to end the execution of the function call and “returns” the result (value of the expression following the return keyword) to the caller. The statements after the return statements are not executed. If the return statement is without any expression, then the special value None is returned.
Yes you can use a fucntion as a condition for if, but that function should return a boolean value (or the value that can be converted to bool by implicit conversion) showing it's success or failure. Like return true if value is added or false if some error occured.
You can simply use
if(queryThis('foo')) { doThat(); }
function queryThis(parameter) {
// some code
return true;
}
Not only you can use functions in if
statements in JavaScript, but in almost all programming languages you can do that. This case is specially bold in JavaScript, as in it, functions are prime citizens. Functions are almost everything in JavaScript. Function is object, function is interface, function is return value of another function, function could be a parameter, function creates closures, etc. Therefore, this is 100% valid.
You can run this example in Firebug to see that it's working.
var validator = function (input) {
return Boolean(input);
}
if (validator('')) {
alert('true is returned from function');
}
if (validator('something')) {
alert('true is returned from function');
}
Also as a hint, why using comparison operators in if
block when we know that the expression is a Boolean expression?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With