Does JavaScript have “Short-circuit” evaluation? [

2019-01-02 20:59发布

问题:

Possible Duplicate:
Using &&'s short-circuiting as an if statement?
Does javascript use optimization in boolean expressions?

I would like to know if JavaScript has "Short-circuit" evaluation like && Operator in C#. If not I would like to know if there is a workaround that makes sense to adopt.

回答1:

Yes, JavaScript has "short-circuit" evaluation.

if (true == true || foo.foo){
    // Passes, no errors because foo isn't defined.
}

Live DEMO

if (false && foo.foo){
    // Passes, no errors because foo isn't defined.
}

Live DEMO



标签: