Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: functions passed as a parameter to an if block

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.

like image 770
Godders Avatar asked Mar 11 '26 13:03

Godders


2 Answers

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.

like image 139
Skilldrick Avatar answered Mar 14 '26 02:03

Skilldrick


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.

like image 33
Nick Craver Avatar answered Mar 14 '26 02:03

Nick Craver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!