One-line if vs && in JavaScript [closed]

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?

Answers:

Answer

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.

Answer

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.

Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.