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?
func开发者_如何学JAVAtion foo(bar) {
if (bar) {
// true
} else {
// false
}
}
This has me puzzled so any help is much appreciated.
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.
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.
You could use typeof() if you want to know what type it returns
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
精彩评论