LESSON 06 – IF STATEMENTS

 

INTRO

 

If statements, also called conditional statements, are statements that allow you to run code if a certain condition is true.  Otherwise, you can skip the code or run different code.

 

IF STATEMENT SYNTAX

 

Here is the general syntax of a simple if statement:

 

if (condition)
{
   code to be executed if condition is true
}

 

It is good practice to indent the code inside the squiggly brackets.

 

Note that you never put a semi-colon at the end of a line with an IF statement!

 

CONDITION

 

A condition is something that will be either true or false.  For example, we can ask if(x < 4) which is said if x is less than 4.

 

OPERATORS

 

We can use the following operators to compare two values.  Note that to check if two things are equal, we must use the double equal sign.  This is a very common error!

 

 

EXAMPLES

 

EXAMPLE 1

 

The following example will check if text field tf1 has a value greater than 5 in it.  The result is shown in text field 2.

 

if(form.tf1.value > 5)

{

   form.tf2.value = "Greater";

}

 

EXAMPLE 2

 

The following example will check if a text field fn contains the value "Patrick".

 

if(form.fn.value == "Patrick")

{

   form.tf2.value = "Hi Pat";

}

 

IF / ELSE STATEMENT SYNTAX

 

The if/else statement allows you to have code that is executed when the condition is true and other code that is executed when the condition is false.

 

if (condition)
{
   code to be executed if condition is true
}
else
{
   code to be executed if condition is not true
}

 

Never put a semi-colon at the end of a line containing an IF or an ELSE.

 

Code inside the squiggly brackets should be indented 3 spaces.

 

EXAMPLES

 

EXAMPLE 3 (similar to Example 1)

 

The following example will check if text field tf1 has a value greater than 5 in it.  The result is shown in text field 2.

 

if(form.tf1.value > 5)

{

   form.tf2.value = "Greater";

}

else

{

   form.tf2.value = "Not Greater";

}

 


Want to learn more?

 

Research the IF / ELSE IF / ELSE statement.

 

Research the logical operators that allow you to combine multiple conditions together.