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

牧云@^-^@ 提交于 2020-01-11 04:30:16

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/34704750/one-line-if-vs-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!