Is there any difference between the following two snippets, or any reason to use one over the other?
if (foo) {
bar();
}
foo && bar();
Is there any difference between the following two snippets, or any reason to use one over the other?
if (foo) {
bar();
}
foo && bar();
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()) {
// ...
}
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.
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().