waxical
waxical

Reputation: 3896

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.

Upvotes: 8

Views: 65016

Answers (5)

VMAtm
VMAtm

Reputation: 28345

You can simply use

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

function queryThis(parameter) {
    // some code
    return true;
}

Upvotes: 11

Saeed Neamati
Saeed Neamati

Reputation: 35822

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?

Upvotes: 5

Jonathan van de Veen
Jonathan van de Veen

Reputation: 1016

This should not be a problem. I don't see anything wrong with the syntax either. To make sure you could catch the return value in a variable and see if that solves your problem. That would also make it easier to inspect what came back from the function.

Upvotes: 1

Pete Duncanson
Pete Duncanson

Reputation: 3246

In sort, yes you can. If you know it is going to return a boolean you can even make it a bit simpler:

if ( isBar("foo") ) {
  doSomething();
}

Upvotes: 3

Barry Kaye
Barry Kaye

Reputation: 7761

Yes you can provided it returns a boolean in your example.

Upvotes: 0

Related Questions