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

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?

Answers:

Answer

It means call bar() only if foo is defined.

Basically the same as:

if (foo){
    bar();
}
Answer

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()
}())
Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.