|
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.
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: An optional else statement can be included with the if statement as
follows: 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.
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.
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.
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:
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 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 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.
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. A better way is to use the and operator, &&. Here is
a rewrite of the script using the and operator. 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.
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. 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. 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.
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: 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: Here is the modified code that replaces the script in the BODY
section. 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. There are no modifications needed in the BODY section. When you press
the test button, the results will be the same.
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.
|