views:

55

answers:

4

In the below code how does passing bar as

 function (n) { return n; } 

to foo evaluate to true in the if block?

 function foo(bar) {

    if (bar) {
       // true
    } else {
       // false
    }
 }

This has me puzzled so any help is much appreciated.

+5  A: 

If bar is bound to an anonymous function, then it is an object. Objects are 'truthy' in JavaScript.

The only values in JavaScript that are 'falsy' are:

  • false
  • null
  • undefined
  • '' (empty string)
  • 0 (zero as a number)
  • NaN

Everything else is 'truthy', including function objects.

If you meant to call the anonymous function, you'd do if (bar(5)) which would call your anonymous function with the argument 5. Then your anonymous function would return n (which is 5 in this case). As 5 is not a falsy object, this would go to the true branch as well. Doing if (bar(0)) would got to the else branch, because 0 is falsy.

Skilldrick
@Skilldrick - thanks for the answer, was most helpful for my more complicated example that the question is extracted from.
Godders
@Godders: More than happy to help :)
Skilldrick
+5  A: 

Anything not null, 0, false, empty string or undefined is going to evaluate to true in an if(something) statement, this is just how weak-typing in JavaScript works.

If you want more specificity you may want to look at the typeof operator to check for the type you're expecting, or use a another stronger check like this:

if(bar === true) {

Using === checks for both value and type equivalence.

Nick Craver
@Nick - thanks also for your answer, helpful too, if I could mark both as the answer I would!
Godders
A: 

You could use typeof() if you want to know what type it returns

joggink
No, you can't. Javascript functions do not have static return types.
SLaks
nevermind, didn't see the reply from Nick Craver.
joggink
A: 

It always return true, because bar is not null. if an expression within an if statement is not a logic expression (e.g. if(x <7)) then performs a check for null. If it is null it returns false, otherwise true.

In your example you have defined bar as the function {returns n;} so that is why your if statement is evaluating to true.

If bar returns a bool (true or false) then you need to call the function and get the result, rather than passing a reference to the function - this is done using parentheses:

var exampleA = bar(false); // executes function bar and returns the result (false) in exampleA
var exampleB = bar; // stores a reference to the function bar in variable exampleB
Giles