I saw somewhere else said,
x && foo();
is equal to
if(x){
foo();
}
I tested it and they really di
It's not exactly equivalent. The first one is an expression with a return value you can use; the second one is a statement.
If you are not interested in the return value (that is, the information whether both x
and foo()
evaluate to a truthy value), they are equivalent, but normally, you should use the boolean-logic version only if you want to use it as a boolean expression, e.g.:
if (x && foo()) {
do_stuff();
}
If you are only interested in running foo()
conditionally (when x is truthy), the second form is to be preferred, since it conveys the intention more clearly.
A reason people might prefer the boolean-logic version might be that javascript is subject to an unusual restriction: source code size (more verbose source code means more bandwidth used); since the boolean-logic version uses less characters, it is more bandwidth-efficient. I'd still prefer the more verbose version most of the time, unless the script in question is used a lot - for a library like jQuery, using optimizations like this is perfectly justifyable, but in most other cases it's not.