20

Is there any meaningful difference between

condition && console.log("this may run");

and

if (condition) console.log("this may run);

If not, which is a best practice?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
orbuch
  • 321
  • 1
  • 2
  • 8
  • Related: *[JavaScript single line 'if' statement - best syntax, this alternative?](http://stackoverflow.com/questions/8860654/javascript-single-line-if-statement-best-syntax-this-alternative/8860674#8860674)* – Peter Mortensen Jan 10 '16 at 14:03
  • 2
    Is very uncommon to use `&&` if you are not assigning the expression to something. – Sulthan Jan 10 '16 at 15:02

3 Answers3

20

You should use the second.

Your code should say what it means. That is what is meant by writing "semantic" code. If you are writing an if condition, then you should use the if statement, because that's what it is there for. The && is, semantically, a logical and, which should be used in cases where you are interested in the logical value resulting from the logical conjunction of two values.

Writing semantic code, as other answers have suggested, makes it easier to write and understand and maintain. As far as this comment goes:

If someone else may need to read or maintain it, then use the second.

Remember that "you six months from now" is "someone else".

Here are some specific reason for using if when you mean if:

  1. If you want to add an else clause, you can just add it. If you have written a && b then you will have to rewrite it as a ? b : c.

  2. Assuming you have used curly braces, as in if (a) { b; }, then you can easily add another step to the body, by writing if (a) { b; c; }. If you had written a && b, then you would need to rewrite this as a && (b, c) or something equivalent; this will not even be possible in some cases, if c cannot function as an expression.

  3. Some linters will (reasonably) complain about a && b.

Note that minifiers will typically convert your second example into the first, so if your rationale for using && is to save bytes, they will be saved anyway by the minifier.

13

There is no difference as such, but you can say that the former one is the shorthand notation of the later one.

I would suggest you to use the later condition, it makes the code more explainable, producing the same results and with the almost the same number of characters.

void
  • 36,090
  • 8
  • 62
  • 107
  • 1
    But there **is** a difference, by definition, in a variety of respects, with the sole exception of behavior. –  Jan 10 '16 at 13:52
7

If only you may ever maintain the code, then use the one you like.

If someone else may need to read or maintain it, then use the second.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
MEC
  • 1,690
  • 1
  • 17
  • 23