3

In JavaScript, how are AND/OR operators actually handled? I'm wondering which of these are more performant or if they do to the same thing internally:

Example A

if ( conditionA && conditionB ) {
    // Do something
}

Example B

if ( conditionA ) {
    if ( conditionB ) {
        // Do something
    }
}

Will example A only evaluate conditionB if conditionA is truthy, or will it always be evaluated, hence taking longer to perform (in the case that conditionA IS truthy) than example B?

Ahrengot
  • 1,579
  • 1
  • 17
  • 29

2 Answers2

6

The && operator is short-circuiting, meaning it will only evaluate the right side if the left side is 'truthy'. So both of your code samples are equivalent. From MDN:

Short-Circuit Evaluation

As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the following rules:

false && (anything) is short-circuit evaluated to false.
true || (anything) is short-circuit evaluated to true.

The rules of logic guarantee that these evaluations are always correct. Note that the anything part of the above expressions is not evaluated, so any side effects of doing so do not take effect. Also note that the anything part of the above expression is any single logical expression (as indicated by the parentheses).

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • Thank you! I want to accept the answer, but it says I have to wait another 13 minutes. Man, Stack overflow is efficient :D – Ahrengot Feb 20 '14 at 15:08
0

Example A and B are practically the same, with 1 difference: In example B you can choose to perform a different action if ONLY condition A = true. This cannot be done in example A.

Laurens
  • 121
  • 1
  • 12