Does a javascript if statement with multiple conditions test all of them?

From a performance standpoint, this is not a micro-optimization.

If we have 3 Boolean variables, a, b, c that is a micro-optimization.

If we call 3 functions that return Boolean variables, each function may take a long time, and not only is it important to know this short circuits, but in what order. For example:

if (takesSeconds() && takesMinutes())

is much better than

if (takesMinutes() && takesSeconds())

if both are equally likely to return false.


That's why you can do in javascript code like

var x = x || 2;

Which would mean that if x is undefined or otherwise 'false' then the default value is 2.


The && operator "short-circuits" - that is, if the left condition is false, it doesn't bother evaluating the right one.

Similarly, the || operator short-circuits if the left condition is true.

EDIT: Though, you shouldn't worry about performance until you've benchmarked and determined that it's a problem. Premature micro-optimization is the bane of maintainability.

Tags:

Javascript