2

Does it make sense to sometimes replace if statements by && statements? By this I mean replace

if(a) {
    b();
}

by

a && b();

Are these forms equivalent? Is the terser style recommended in some situations?

Randomblue
  • 98,379
  • 133
  • 328
  • 526
  • Possible dup: http://stackoverflow.com/questions/6970346/what-is-x-foo – bbg Oct 29 '11 at 16:24
  • Just to add more to what others have said, they will behave equivalently, except that 1) jslint and similar tools may complain about the second. 2) the second returns a value, not that you're capturing it. – thomasrutter Oct 29 '11 at 16:27
  • @thomasrutter As Doug said jslint with hurt your feelings – david Oct 29 '11 at 16:32

2 Answers2

5

Yes, they are equivalent. Of course the if is much more readable.

The && is the logical AND operator, for efficient evaluation, it can short cut: if the left hand part of the statement returns a falsy value, the second part is not evaluated and the whole expression will return false.

If the left hand part of the statement instead has a truthy value, the second part is evaluated in order to determine the result.

With your expression a && b();, you're using a side effect of this operator (the short cut mechanism), you're not using the logical AND operation result. While it works, I would not recommend it.

stivlo
  • 77,013
  • 31
  • 135
  • 193
2

Both the forms are more or less equivalent. However, there is one subtle difference:

If statements are just statements. They do not return or express a value.

The logical AND operator forms an expression. It returns or expresses a value.

It generally not a good idea to use an expression in place of a statement. It could lead to unexpected results. For example, when used in a bookmarklet if the expression is not voided then the document is replaced by the expression.

As a general rule always use the if statement for code branching, use the conditional operator to express one of two different expressions, and use the logical AND and OR operators as guard and default expressions respectively.

The concept of statements and expressions are fundamental to all languages. Even natural languages (compare with sentences and phrases). We use both of them for a reason. It's generally not a good idea to mix them up. Besides, they serve as a form of documentatiom for other programmers and are easier to read and debug.

Hope this post doesn't fall on oblivious ears. =)

Aadit M Shah
  • 67,342
  • 26
  • 146
  • 271