if Statement, Boolean, Functions and Variable Scope
(Lesson 5)

This lesson introduces you to two essential constructs of the JavaScript language, the if statement and the function.

The if statement is used to make decisions in JavaScript. Boolean operators are also discussed in this lesson because they are used in along with the if statement.

The function allows you to repeat specific JavaScript statements anytime you want by calling the same statements without writing new ones. For example, if I want to add two numbers at several different locations in my program, I can just write the code one time and designate it as a function. Then I can call that function anytime I want to add two numbers. Understand that the two numbers do not have to be the same but can be specified at the time that the function is called.

The final topic of this lesson is variable scope. Scope determines what parts of your program can read and change the contents of a variable.


if Statement

The if statement is one of the most used features of JavaScript. It is basically the same in JavaScript as it is in other programming languages. If you are new to programming, you should spend some time understanding how the if statement works.

You use the if statement in JavaScript to make decisions. The syntax for it is as follows:

 if (condition){
   statements
   }
The if keyword identifies this as an if statement. The condition in the parenthesis ( ) is evaluated to determine if true, and if so then the statements inside the curly braces { } are executed, otherwise they are skipped and the programs continues with the first line after the if statement.

An optional else statement can be included with the if statement as follows:

 if (condition){
   statements
   }
 else{
   statements
   }   

In this case, the statements inside of curly brackets { } after the else keyword are executed if the condition of the if statement is false.

Take a look at the following table which shows the results expected from the if statement for different conditions. In this table x and y are two variables that have been initialized to a value.

if statement Results
condition   returns true if
x == y x and y are equal
x != y x and y are not equal
x > y x is greater than y
x >= y x is greater or equal to y
x < y x is less than y
x <= y x is less than or equal to y

I have posted a script containing a simple if statement in our electronic chalkboard below. Let's use it to test the if statement to discover how it works with each of the conditions shown in the "if Statement Results" table.


Electronic Chalkboard
   

Take a close look at the script. It contains a variable num which is initialized to 4 and an if statement that is true if num == 4. Note that this is the condition shown in the first row of our table. When you press Test, the HTML code is loaded into a small pop-up window so you can see the results. So press Test now and you will see the following in the pop-up window.

Testing if statement
Satisfied!
rest of program starts here

Change the value of the num variable to some number other than 4, for instance try 3 (i.e. change the line var num = 4 to var num = 3). Now the requirements of the if statement will not be satisfied and you will get the following when you press Test:

Testing if statement
rest of program starts here

Thus, the value of our variable num must be equal to 4 for the code between the curly braces of the if statement to be executed. Any other value of the variable will cause this code to be ignored.

Now lets test the second condition in our table. We want the if statement to be satisfied when num is not equal to 4. Change the if condition for our script to
num != 4, i.e. replace num == 4 with it. Then test it by setting the variable num to different values. The results should be the opposite from our first case.

To test the third condition in the table, we want the if statement to be satisfied if num is greater than 4. So replace the if condition for our script with
num > 4. Now test it with several values for num. You will find that the if condition is satisfied for the values 5 and 10 but not for 1 or 4.

Replacing the if condition with num >= 4 will result in almost the same results as our previous case except the if statement will now also be satisfied when num = 4.

Try the last two conditions in our table, num < 4 and num <= 4. This means that the variable num will need to be less than 4 in the first case and less than or equal to 4 in the second case for the if statement to be satisfied.

Here is a simple problem for you to solve using an if statement. You will also be using the else statement to solve this problem. I recommend that you save your results because you will be modifying it in one of your class assignments. Suppose you must get a grade of 70 or better to get a passing grade for this class. Write a script that will test to see if you passed and will display the results in the browser. You may want to compare my solution and source with yours after you get it completed and tested.


Boolean Operators

Suppose you wanted the previous script to display a letter grade instead of passed/failed. You would want to display A for a 90 or above, B for a grade 80 or above but less than 90 and ETC. To determine a B you could nest if statements as shown below. This can get real messy and require a lot of code.


if (grade < 90){
  if (grade >= 80){
    document.write('You got a "B"')
    }
  }

A better way is to use the and operator, &&. Here is a rewrite of the script using the and operator.


if (grade < 90 && grade >= 80){
  document.write('Grade is a "B"')
  }

The and operator, && , allows you to combine two conditions so that both must be true to satisfy the if condition. Another Boolean operator is the or operator, ||, which combines two conditions such that the if statement is satisfied if either condition is true. The third boolean operator is the Not Operator, !, which makes a condition that returns true, false and vice versa.

Look again at the above script and notice that phrase 'Grade is a "B"' contains both double quotes and single quotes. This is the way you can put quotes inside of quotes in JavaScript.


Functions

What if you wanted to use our grading script for more than one student? You would have to repeat it for each student. This could get quite lengthy if there were more than a very few students. You can however use a function to contain the script and call it every time your need it. Here is the syntax for a function.

 function name (parameters){
   statements
   }

The function keyword identifies this as a function. The parameters in the parenthesis ( ) provide a means of passing values to the function. There can be as many parameters separated by commas as you need. It is perfectly ok to have a function with no parameters. These parameters are variables which are used by the JavaScript statements inside the curly braces { }. The var keyword is not needed to declare the parameters in a function as variables because they are automatically declared and initialized when the function is called. The function can return a value by using the return keyword.

You should put your functions in the HEAD section of your document. Functions will work if you put them in the BODY section. However, a function must be loaded prior to the statement that calls it. Putting all functions in the HEAD section is the way to insure this.

The best way to demonstrate a function is with an example. Suppose we want to make a function that we can call anytime to add two numbers together. Here is one way of writing the function.

 function myAdder (num1, num2){
   var total = num1 + num2
   document.write(total)
   }

You would place this function inside some <SCRIPT> tags in the head section. You then can call the function from anywhere in your document. In this example, lets call it from within some <SCRIPT> tags in the body of document like this.

  myAdder(23, 56)

Lab Time     

Lets try this function in our lab. Type the above myAdder() function between some <SCRIPT> tags in the HEAD section (note that the script tags are not automatically placed in the HEAD section for you, so you will have to put them there yourself). Then place the call to the function in the <SCRIPT> tags in the BODY. The results when your press Test should be 79.

Add the following two lines to the script in the BODY section to demonstrate how to call the function a second time:

  document.write("<BR>")
  myAdder(100, 480)

Ok lets try a variation to the function that we wrote in our last lab experiment. This time we will let the function return the value rather than print it to the document. Then, we will print the returned value to the document from the BODY section. Modify our function in the head section so that it looks like this:

 function myAdder (num1, num2){
   var total = num1 + num2
   return total
   }

Here is the modified code that replaces the script in the BODY section.

  document.write(myAdder(23, 56))
  document.write("<BR>" + myAdder(100, 480))

When you test this new version, the results should be the same as we got above. You will want to use the first method sometime and the second on others. It will all depend on exactly what you are doing.

In our last lab experiment, there is no need to have the variable total in the function. Out last modification for this exercise will be to modify the function as shown below.

 function myAdder (num1, num2){
   return num1 + num2
   }

There are no modifications needed in the BODY section. When you press the test button, the results will be the same.


Scope of Variables

A variable that is defined outside of a function is a global variable. A variable that is defined inside of a function is a local variable. What does this mean? Global variables can be used anywhere in the document that is currently loaded in the browser. They can be declared in the HEAD section and used in any function or even in the BODY section. Local variables can only be used in the function that declares them. Yes, you could leave the var keyword off of the variables you declare inside of a function and they will then be global. I do not recommend this.



Assignment

  1. This problem involves modifying the pass/fail script that we developed during our discussion of the if statement. Write a script that contains a function that you can pass a grade as a parameter and have it display a passed or failed condition. Demonstrate the functions by printing out the pass/fail status for five students.
    Solution   Source

  2. Make a further modification to our pass/fail function so that the results are returned to the portion of the BODY section that called it and then displayed in the document.
    Solution   Source

  3. Make a final modification to the script that we did in problems 1 and 2 so that a letter grade is displayed instead of pass or fail. This letter grade should be based on the following:
        A is a grade of 90 or greater
        B is a grade of 80 or greater, but less that 90
        C is a grade of 70 or greater, but less than 80
        F is any grade below 70
    I recommend that you add a few more student names and grades so that the script is adequately tested.
    Solution #1   Source #1       Solution #2   Source #2       Solution #3   Source #3
    As shown here, there are many solutions to most problems. There are many others in addition to these 3.



[ Top of Page  |  Contents ]