Like many other languages Javascript’s && and || operators short-circuit evaluations,that is, for
This means that in the following expression, x will never be compared to y.
true || x == y
This short-circuiting is great for performance, as it allows significant bits of calculations to be skipped. In addition to that, it lets you to write e.g. the following in one expression without getting an ‘object has no properties’ error:
oNode && oNode.firstChild
Be mindful though when using && with code that has side effects, e.g. say you have two objects with a hasError() method which return true or false depending on whether an error occurred and additionally output an error message:
x.hasError() && y.hasError()
Here, if x has an error, y will never be evaluated and thus the error message will never be shown.
For more details pls visits this and that.
&& if the first operand evaluates to false, the second operand is never evaluated because the result would always be false.Similarly, for
|| if the result of the first operand is true, the second operand is never operated.
This means that in the following expression, x will never be compared to y.
true || x == y
This short-circuiting is great for performance, as it allows significant bits of calculations to be skipped. In addition to that, it lets you to write e.g. the following in one expression without getting an ‘object has no properties’ error:
oNode && oNode.firstChild
Be mindful though when using && with code that has side effects, e.g. say you have two objects with a hasError() method which return true or false depending on whether an error occurred and additionally output an error message:
x.hasError() && y.hasError()
Here, if x has an error, y will never be evaluated and thus the error message will never be shown.
For more details pls visits this and that.
No comments:
Post a Comment