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.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With