devxlogo

Arrange Conditions Properly

Arrange Conditions Properly

You can optimize the performance of your “JavaScript” code by properlyarranging the conditions in the “if” statement. If you have severalconditions to be tested together, and you know that one is more likely topass or fail than any of the others, depending on whether the tests areconnected with OR (||) or AND (&&), you can speed execution of your scriptby putting that condition first in the conditional statement.

For example, if three conditions must all be true (using && operators) andthe second test fails, the third condition is not tested. Similarly, ifonly one of several conditions must be true (using || operators), testingstops as soon as any one condition passes the test. This is particularlyeffective if the conditions to be tested involve execution of function callsor other code.

In this example, the second part of the condition will not be evaluatedif the first part of condition returns true. Notice that in thiscase it will save you a function call.

 if ((firstfunction() == true) || (secondfunction() === true)){    // code}else{    // code}

devx-admin

Share the Post: