what does variableFoo && functionBar() do in javascript?

心已入冬 提交于 2019-12-24 05:46:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!