Short circuit evaluations on && and || in JavaScript

Like many other languages Javascript’s && and || operators short-circuit evaluations,that is, for

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

Comments

Popular posts from this blog

The model backing the 'MyDBContext' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the DropCreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data.

How can I get a value of a property from an anonymous type (C#)

Check/Uncheck all items in a CheckBoxList using Javascript