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(){

    // do something
   } else {
    // do something else       

   foo && bar();


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?



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

Basically the same as:

if (foo){

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


(function () {
  if (foo) return bar()
  else return foo

You can also do the reverse using || which is more like:

if (!foo) bar()


(function () {
  if (foo) return foo
  else return bar()


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.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.