6

In Javascript, specifically Google's V8 engine, does writing multiple function calls in a list of or conditions '||' execute all of the functions before determining the final result of the if comparison?

e.g.

var path = 'C:\\MyFiles\\file.doc';
if (   path.match(/\.docx?/gi)
    || path.match(/\.xlsx?/gi)
    || path.match(/\.xml/gi)
    || path.match(/\.sql?/gi)) {

    // Success
} else {
    // Failed
}

So I would like to ask: Is this similar to how the '&&' conditions work, but the opposite? Will the first condition evaluating to TRUE cause the remaining to be skipped and the Success logic to be executed?

I cannot find this stated in any documentation that I am looking for. It is not like this will make a huge difference, however I am curious as to how this is actually executing.

(By similar to the And '&&' I mean that the first condition evaluating to FALSE will stop the remaining conditions from executing and proceed to following else.)

Don Duvall
  • 839
  • 6
  • 10
  • 1
    Yes, `||` short-circuits, just like `&&`. In this particular case, however, you might be better off with one single regular expression: `if(path.match(/\.(sql|xml...etc)` – georg Nov 18 '14 at 19:11
  • A good way to prove this is by creating one function that always return true and another one that always return false, and then test by calling them in different orders. Example: http://jsfiddle.net/79j6j5yw/ – Guilherme Sehn Nov 18 '14 at 19:21

1 Answers1

11

You're right. It's called short circuit evaluation, and it applies to both || and &&.

For ||, evaluation of the right hand side takes place only if the left hand side evaluates to false.

For &&, evaluation of the right hand side takes place only if the left hand side evaluates to true.

Note that it's not just for performance. It also prevents errors from occurring: sometimes evaluating the right hand side would be unsafe or meaningless if the left hand side were not as expected.

chiastic-security
  • 20,430
  • 4
  • 39
  • 67