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.
If
baris bound to an anonymous function, then it is an object. Objects are ‘truthy’ in JavaScript.The only values in JavaScript that are ‘falsy’ are:
falsenullundefined''(empty string)0(zero as a number)NaNEverything 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 argument5. Then your anonymous function would returnn(which is5in this case). As5is not a falsy object, this would go to thetruebranch as well. Doingif (bar(0))would got to theelsebranch, because0is falsy.