Conditions are commonly used in programs to make a condition become a flow control mechanism.
Flow control is a method of controlling which way a program will flow and it works by assessing a condition and deciding which route to take.
The first flow control mechanism introduced in this tutorial is the if statement.
If statements
An if statement has a simple syntax:
if(condition) { //Do something }
If the condition is satisfied then the code inside the if statement will be executed, that is if there is any code inside it:
if(true && true) { //Do something alert("Inside the first if statement") } if(true && false) { //This should not be reachable alert("Inside the second if statement") } alert("Outside both if statements")
Else
If a condition is not satisfied with an if statement nothing will be executed. If an
else
keyword follows the closing brace of the if statement the
if statement has an alternative path to follow. This is sometimes called an if-else statement:
if(true && false) { //This should not be reachable alert("Inside the if statement") } else { //This should be reached alert("Inside the else statement") }
Else if
The final kind of if statement is an if-else if statement (or one that includes a final else statement which
is sometimes known as an if-else if-else statement). This final kind of if statement allows multiple
conditions to be assessed in one if statement using the else if
keywords:
if(true && false) { //This should not be reachable alert("Inside the if statement") } else if(false || true) { //This should be reached alert("Inside the first else if statement") } else if(false || true && true) { //This should not be reached alert("Inside the second else if statement") }
If the if in the statement is not true it will flow down to one of the else if statements. As shown above, there can be multiple else if statements but only one of them will execute, and the one that executes will always be the first one that is satisfied.
Else if statements can also contain an else which will be triggered whenever something not handled by the if or the else if statements occurs:
if(true && false) { //This should not be reachable alert("Inside the if statement") } else if(false || false) { //This should not be reached alert("Inside the else if statement") } else { //This should be reached alert("Inside the else statement") }