5

Is there any difference between the following two snippets, or any reason to use one over the other?

if (foo) {
    bar();
}

 

foo && bar();
Phil K
  • 4,939
  • 6
  • 31
  • 56

3 Answers3

14

The second form is known as short-circuit evaluation and results in exactly the same as the first form. However the first form is more readable and should be preferred for maintainability.

This type of short-cuircuit evaluation is often seen in if-statements, where the right hand is conditionally evaluated. See the example below; bar is only evaluated if foo evaluates to true.

if (foo && bar()) {
    // ...
}
Bouke
  • 11,768
  • 7
  • 68
  • 102
3

The version foo && bar() is an expression, and thus has a value:

var result = foo && bar();

When using the if version, the above might look like this:

var result;
if (foo) {
    result = bar();
}

which is more verbose.

user123444555621
  • 148,182
  • 27
  • 114
  • 126
2

The answer of bouke with the short-cuircuit evaluation is really good. But I like to add that a good coding style is the use of the if-statement, if the call of bar() has no boolean-return-value and no further condition has to be satisfied using bar().

Mr.Mountain
  • 863
  • 8
  • 32