问题
I have come across some Javascript code recently that looks like this:
var foo = 'blah';
bar = function(){
// append some content to the body
}
doStuff = function(){
if(somethingIsTrue){
// do something
} else {
// do something else
}
foo && bar();
}
doStuff();
The foo && bar() expression logs to the console as 'undefined'.
I get why it might call the bar function to run from inside the doStuff function but why is it used as a comparison expression with the foo variable?
回答1:
It means call bar()
only if foo
is defined.
Basically the same as:
if (foo){
bar();
}
回答2:
It makes use of the short circuiting logic of &&
. Because if the left hand side of the &&
expression is false
, we already know the value of the entire expression is false
so we don't need to evaluate the right hand side. So this will evaluate to the left hand side if foo
is falsy and the right hand side if foo
is truthy.
In simple terms, it can be thought of as:
if (foo) bar();
but it's also an expression, so it's more like:
foo ? bar() : foo
or
(function () {
if (foo) return bar()
else return foo
}())
You can also do the reverse using ||
which is more like:
if (!foo) bar()
or
(function () {
if (foo) return foo
else return bar()
}())
回答3:
Source
Javascript uses short-circuit evaluation. That means that if foo
evaluates to a truthy value (i.e., it's defined), then it will evaluate bar
.
来源:https://stackoverflow.com/questions/20101852/what-does-variablefoo-functionbar-do-in-javascript