Controlling the Flow of Execution?
Fairly often, you need a script to do different things under different conditions. For example, you might write a script that checks the time every hour, and changes some parameter appropriately during the course of the day. You might write a script that can accept some sort of input, and act accordingly. Or you might write a script that repeats a specified action.
There are several kinds of conditions that you can test. All conditional tests in Javascript are Boolean, so the result of any test is either true or false . You can freely test values that are of Boolean, numeric, or string type.
Javascript provides control structures for a range of possibilities. The simplest control structures are the conditional statements.
Using Conditional Statements
Javascript supports if and if...else conditional statements. In if statements a condition is tested, and if the condition meets the test, some Javascript code you've written is executed. (In the if...else statement, different code is executed if the condition fails the test.) The simplest form of an if statement can be written entirely on one line, but multiline if and if...else statements are much more common.
The following examples demonstrate syntaxes you can use with if and if...else statements. The first example shows the simplest kind of Boolean test. If (and only if) the item between the parentheses evaluates to true , the statement or block of statements after the if is executed.
Tip If you have several conditions to be tested together, and you know that one is more likely to pass or fail than any of the others, depending on whether the tests are connected with OR (||) or AND (&&), you can speed execution of your script by putting that condition first in the conditional statement. For example, if three conditions must all be true (using && operators) and the second test fails, the third condition is not tested.
Similarly, if only one of several conditions must be true (using || operators), testing stops as soon as any one condition passes the test. This is particularly effective if the conditions to be tested involve execution of function calls or other code.
An example of the side effect of short-circuiting is that runsecond will not be executed in the following example if runfirst() returns 0 or false .
if ((runfirst() == 0) || (runsecond() == 0)) // some code

