Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In JavaScript, does an if with multiple or's evaluate all statements before continuing? [duplicate]

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.)

like image 520
Don Duvall Avatar asked Feb 12 '23 13:02

Don Duvall


1 Answers

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.

like image 163
chiastic-security Avatar answered Feb 15 '23 10:02

chiastic-security