Skip to main content

Selection using Branching

Statements in a JavaScript program generally execute in the order in which they appear, one after the other. Most programming languages provide flow control statements that let you control the order in which code is executed. One of the most important features of a computer language is the capability to test and compare values. This allows your scripts to behave differently based on the values of variables, or based on input from the user.

The if statement is the main conditional statement in JavaScript. This statement means much the same in JavaScript as it does in English-for example, here is a typical conditional statement in English:

 
If the phone rings, answer it.
 

This statement consists of two parts: a condition (If the phone rings) and an action (answer it). The if statement in JavaScript works much the same way. Here is an example of a basic if statement:

 
if (a == 1) window.alert("Found a 1!");
 

This statement includes a condition (if a equals 1) and an action (display a message). This statement checks the variable a and, if it has a value of 1, displays an alert message. Otherwise, it does nothing. If you use an if statement like the preceding example, you can use a single statement as the action. You can also use multiple statements for the action by enclosing them in braces ({}), as shown here:

 
if (a == 1) {
   window.alert("Found a 1!");
   a = 0;
}
 

This block of statements checks the variable a once again. If it finds a value of 1, it displays a message and sets a back to 0.

Next: Conditional Operators