What is “x && foo()”?

前端 未结 5 1866
遇见更好的自我
遇见更好的自我 2020-11-22 13:34

I saw somewhere else said,

x && foo();

 is equal to

if(x){
    foo();
}

I tested it and they really di

5条回答
  •  情话喂你
    2020-11-22 13:50

    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.

提交回复
热议问题