8

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.

2
  • 2
    looks right to me, though I would use !== false instead. Commented Jul 15, 2011 at 11:31
  • Perhaps you should post the problematic code with the syntax errors instead of this simple example that you could easily test for yourself. Commented Jul 15, 2011 at 13:48

5 Answers 5

11

You can simply use

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

function queryThis(parameter) {
    // some code
    return true;
}
Sign up to request clarification or add additional context in comments.

4 Comments

Also interesting: why is return from if not possible as in Elixir
@Timo What do you mean by not possible? You can do if (some_check) { return 1; } else { return 0; }? Is it some kind of comment for advertise the other language?
It is not related to the question, the ternary op is what I was looking for: x = true?1:2
@Timo, oh, ok, sorry, didn't understand that first time.
5

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?

Comments

3

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

Comments

1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.