Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using function's return value in if statement

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.

like image 243
waxical Avatar asked Jul 15 '11 11:07

waxical


People also ask

Can you return a value in an if statement?

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

Can you put a return inside and if statement?

Yes, you can use the nested usage of IF. Example: IF( Condition1, True,IF(Condition2,True).

How do you return a value from an IF statement in Python?

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.

Can we use function in if condition?

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.


2 Answers

You can simply use

if(queryThis('foo')) { doThat(); }

function queryThis(parameter) {
    // some code
    return true;
}
like image 68
VMAtm Avatar answered Oct 04 '22 16:10

VMAtm


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?

like image 45
Saeed Neamati Avatar answered Oct 04 '22 17:10

Saeed Neamati