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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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. =)