2

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?

Mark
  • 622
  • 11
  • 27

3 Answers3

6

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

Basically the same as:

if (foo){
    bar();
}
Vic
  • 8,261
  • 6
  • 42
  • 55
  • 2
    +1. It's quite a common pattern I think, while I find the benefits (short) aren't worth loosing in readibility... – Laurent S. Nov 20 '13 at 16:51
  • I agree the readability in this case is poor, and you aren't gaining much. The "or" version, IMO, o.k. cause it is so useful to test for missing data or nulls and use a default, e.g. `currency = someoption.currency || 'dollars'`. – user949300 Nov 20 '13 at 16:54
  • @user949300 I don't think `or` would make sense in this case, since `foo` is the condition for evaluating `bar()`. –  Nov 20 '13 at 16:57
  • @remyabel I think user949300 is just talking about the common practice to use `||` as a way to assign default values. Similar concept to using `&&` as a stand in for an `if...else`, but I don't think he's suggesting that they're interchangeable. – sbking Nov 20 '13 at 17:04
2

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.

Community
  • 1
  • 1
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()
}())
ForbesLindesay
  • 10,482
  • 3
  • 47
  • 74