Using JavaScript
to Teach Programming Concepts
[Programming Foundations - A First Course]
By
Professor Tom Adamson
Assistant Professor, Information Technology
Southern New Hampshire University
Contents Copyright © 2001, Tom Adamson
Abstract
The traditional method of teaching
programming is through separate programming courses, each dedicated to a
specific programming language. This
method of teaching programming leads the student to believe that each
programming language is a distinct and separate entity. In the field of programming, there will
always be a “new and emerging” language.
Thus, more than understanding the current languages, students must be
prepared to understand the new ones and the future derivatives of the current
ones. When it comes to programming
languages, students must see the commonalties and where there are differences,
then the correlation between the differences and then the repetitive patterns
of the correlations. The best
professional programmers are the ones who are able to stay employed through
changing times. These are the ones who
are able to translate what they now know into what they need to know. That is the purpose of this document’s
approach to programming - To help students transfer current concepts into
future skills.
The purpose of this document is to
assist the teacher in developing a pedagogy
for teaching programming in a way that emphasizes the correlations
common to all programming languages.
The pedagogy focuses on the development of good programming
practices. These programming practices
require the student to use a step-by-step process in converting a problem statement
into a workable computer program. The
programming language of JavaScript was chosen because it allows an early
introduction to object oriented analysis and has a syntax that is almost
identical to that of other higher level languages such as C, C++, C#, and Java.
JavaScript
is not Java. JavaScript, is a platform
independent programming language that needs only a current web browser and a
simple text editor for its development and implementation tools. JavaScript can be used as the vehicle to
teach Object-Oriented as well as Procedural concepts in programming. JavaScript can also be used to demonstrate
the concepts of Top-Down design and modular programming using separate user
developed functions, The language has
built-in functions which may be used to teach library functions. Its syntax closely resembles that of higher
level languages such as C and C++, C# and Java. It is capable of performing all of the fundamental programming
constructs such as:
· Declaring Variables
· Variable Types
· Arithmetic including built-in arithmetic functions.
· Logic (if, then, else)
· Arrays (simple and multidimensional)
· Iteration (do-while, repeat until)
· Recursion
· Functions (with and without arguments)
· Objects (with methods, attributes, and events)
· String Manipulation
· Math Methods
· Date Methods
· User Defined Objects
· Interface Design with the Browser (buttons, drop-down menus,
etc.)
· Multimedia (sound, graphics, and animation) - Great for
motivation!
Using
JavaScript to teach programming concepts does not require any programming
language as a prerequisite. Thus it may
be presented to the student early in their programming studies.
This
paper contains many teacher-ready
examples for using JavaScript to teach programming concepts. Teachers may
freely select from the following Contents to meet the needs of their
students. It should be clear that
JavaScript offers a wide variety of programming concept options, which are
available in higher level languages, without the interface and cost overhead
associated with them.
Contents:
1.
A Brief History of
JavaScript
2.
Advantages of
JavaScript for the Student and Teacher
3.
Setting-up Your
Computer to Start JavaScript
4.
Your First JavaScript
Program - Using the Document Object to Change the Browser’s Properties
5.
An Overview of
Programming Languages
6.
Variables and Their
Use
7.
Rules for Creating
Variables
8.
The Input - Process - Output Model
9.
Program Development with Functions
10. Program Development with Structures
11. Creating and Using Data Files
12. Program Development with Objects
13. Arithmetic Operators
14. Comparison
Operators
15. Assignment Shorthand Operators
16. Logical Operators
17. Arrays
18. Program Interaction with Databases
19. Putting the for Loop to Work
20. Control Structures - The if, if-else, and switch
Statements and the Conditional Operator.
21. Loops - do
while and while do.
22. Functions with Parameters
23. Local and Global Variables
24. The string
object.
25. Interpreter Design Principles
26. The math
object.
27. Programming with Mathematical Functions
28. The date
object.
29. User Input Interface Design
30. Program Output Interface Design
31. Building Programs from Existing Information -
Case Studies
32. Built-in Library Functions
33. Nesting
Control Structures
34. Multiple Control Structures
35. Debugging and Testing Programs
36. Recursive Mathematical Functions
37. Problem Solving with Recursion - Case Study
38. AI Concepts with JavaScript
39. Data Mining
40. Expert Systems - Case Study
41. Using JavaScript with Binary Search Trees
42. Emerging Technologies - XML Concepts
43. Emerging Technologies - XHTML Concepts
44. Emerging Technologies - XSL Concepts
1. A Brief
History of JavaScript
JavaScript started life as
“LiveScript”. LiveScript was born in
the Netscape programming factory back in 1996.
At that time, Netscape was planning its new features for its Netscape
Navigator 2.0 product to be released in January of that year. LiveScript was originally designed to
augment HTML documents. It was
developed for the average Web page designer.
So the idea was to keep a simple syntax, with an easy-to-use interface.
LiveScript’s reception by Web folks
was met with low interest in this new programming language. Most of this was due to the frenzy
surrounding newly announced Java. Java
was a more robust programming language developed by Sun Microsystems. Many Web folks were working hard to use Java
as a means of making Web pages more dynamic and interactive.
Netscape then announced its
intention to support Java in its Netscape 2.0 product and to further
collaborate with Sun Microsystems to re-engineer its LiveScript programming
language, which was now re-named JavaScript.
And presto! The “little
scripting language that could” blossomed.
There are several reasons for the
success of JavaScript. First, it works
in all popular browsers (were VBScript does not). Whereas Java requires in-depth programming knowledge and a rather
complex software-development kit, JavaScript programs can be written and
executed by beginning programmers using little more then a simple text editor
and current browser.
2. Advantages of
JavaScript for the Student and Teacher
From the
student’s and teacher’s standpoint, the use of JavaScript as the vehicle for
learning programming concepts, has the following advantages:
· JavaScript does not require any extra purchase of software.
· JavaScript does not require any installation.
· JavaScript does not require any site-license to use.
· JavaScript does not require any extra hard-drive or computer memory space.
· JavaScript is platform independent and my be used on any Internet appliance that supports a JavaScript enabled browser.
· You do not have to have an Internet connection.
· JavaScript is easy to learn.
· The syntax of JavaScript is similar to that of higher-level languages such as C and C++, C#, and Java
· JavaScript’s interactive features can make learning fun and motivational.
· JavaScript is powerful enough to provide Computer-Aided Instruction.
· JavaScript may be used to teach beginning object oriented design concepts.
· JavaScript can be used to teach interactive mode, batch mode, and data file concepts.
· JavaScript easily integrates with HTML, XHTML, and XML. The advantage here is the ability to expose the student to the latest network technologies for new and emerging Internet appliances.
Since the interface for JavaScript
is a simple text editor, both teacher and student are forced to concentrate on
programming concepts. The advantage of
this simple interface is that students and teachers cannot use
“point-and-click” methods to develop code.
In this way, a group of teachers can help assure consistency in
instructional goals, and stay focused on their given tasks.
Once a student has a firm grasps of
programming concepts and how to translate problem statements into actual
workable code, they will then have the necessary background for program
development in other high-level programming languages.
What follows is a sample JavaScript
program.
<script>
/*************************************/
/*
Total Cost */
/*************************************/
/* Developed by: A. Good Programmer */
/*************************************/
/*
This program will take the cost
*/
/* of
a product and the sales tax
*/
/*
rate, then compute the total. */
/*************************************/
/* Functions Used */
/*----------------------------------------------------*/
/* Explain_Program() */
/* Explains the purpose of the */
/* program to the user. */
/*---------------------------------------------------*/
/* Get_Purchase() */
/* Prompts the user to enter the */
/* amount of purchase. */
/*--------------------------------------------------*/
/* Get_Tax() */
/* Prompts the user to enter the */
/* sales tax rate. */
/*--------------------------------------------------*/
/* Compute_Total(amount, rate) */
/* Computes the total cost of the */
/* purchase. */
/* amount = amount of the purchase. */
/* rate = the sales tax rate. */
/*--------------------------------------------------*/
/* Display_Results(total) */
/* Displays the total cost to the */
/* program user. */
/* total = total amount of purchase. */
/**********************************/
main();
//Call function main()
function main() //Executes the other
functions.
{
var amount; //amount of the purchase
var rate; //the tax rate
var total; //total amount of the sale
Explain_Program();
amount = Get_Purchase();
rate = Get_Tax();
total = Compute_Total(amount, rate);
Display_Results(total);
}
function Explain_Program()
//Explains the program.
{
document.write("This program will
compute ");
document.write("the total cost of an
item ");
document.write("based upon its
purchase price ");
document.write("and sales tax
rate.");
}
function Get_Purchase()
//Gets the purchase amount.
{
amount = prompt("Enter the purchase
price: ", "");
return(amount);
}
function Get_Tax()
//Gets the tax rate.
{
rate = prompt("Enter the tax rate:
", "");
return(rate);
}
function Compute_Total(amount, rate)
//Computes the total sale price.
{
var tax; //Amount of tax for the item
var total; //Total cost of the item
tax = amount * rate;
total = parseFloat(amount) +
parseFloat(tax);
return(total);
}
function Display_Results(total)
//Displays total cost to the user.
{
document.write("<br> Your
total cost is: ");
document.write("$" + total);
}
</script>
The first striking feature to
observe about the above program is that its syntax is almost identical to that
of C, C++, C#, and Java. This cannot be
said of BASIC, which has its own unique syntax.
The
syntax and ease of use of JavaScript should be enough to convince the reader of
its use for teaching programming concepts.
But there is more. Note from the
above program that the problem is broken down into separate functions (each one
with a separate and unique task). This
approach encourages the student to break any programming problem down into its
component parts and then structure the relationship between these parts to form
the whole program. This is exactly the
same method which may be used in C, C++, C#, and Java. Once the student understands the programming
concepts, syntax, and problem-solving approaches using JavaScript, the transition
to other higher-level languages should now be an easy process.
Bye
the way. The above program really works
in the IE5 browser. Try it out. No site license required.
3. Setting-up
Your Computer to Start JavaScript
For the examples used in this
document, the Microsoft Internet Explorer 5.0 browser is used on a Microsoft
Windows platform. This browser was
selected because of its ease of use and it is free. With this browser, the student and teacher may view their source
code and executable results at the same time.
This provides a great student-teacher environment for learning
programming concepts where both can get instant feedback from new code. The Microsoft Windows platform was selected
because, at the time of this writing, it is the most common platform used in
schools.
It should be noted that the
Microsoft IE browser does not actually use JavaScript but uses Microsoft’s
JScript. JScript is Microsoft 's extended implementation of ECMAScript
(ECMA262), which is an international
standard based on the Netscape 's JavaScript and Microsoft's JScript languages.
JScript is implemented as a Windows Script engine. However, for our purposes here, we be using commands that support
both JavaScript as well as JScript.
To set up your computer, go to the View menu from any Window.
(You may do this by right-clicking on your screen’s desk-top, then from
the resulting pop-up menu go to New
and then select Folder. You will then have a new window). From the View menu choose Folder Options. From the resulting dialog box click on the View tab. In the new dialog
box uncheck the “Hide file extensions for known file types” check box. Click the OK button. You will now see
file extensions for your known file types.
That is, you will see .txt for text files, .doc for Microsoft Word
documents, and .htm for HTML documents.
Once you have done this, all you
need to do now is create a folder on the desktop. You can name it MyJavaScript.
Open the folder, and with your mouse pointing on blank space in the folder,
right click and a pop-up menu will appear.
From that menu select New,
and an extended pop-up menu will appear.
From there select Text Document. Once you have done this, you will see a text
document icon with the name “New Text Document.txt”. You may rename this to lesson1.txt (be sure to add the .txt file
extension so Windows knows it is a text document).
Now open the text document, you will
see that it is blank (you haven’t put anything into it yet). Once opened, type: Hello World! Then
close the document being sure to Save its contents. Next change the extension of this text document from .txt to .htm
(you will change it from lesson1.txt to lesson1.htm). You will then get a dialog box with a warning on it that changing
this extension may make the document unstable (changing from .txt to .htm will
not cause any instability), You will be
asked if you are sure you want to change it; you do, so click on the Yes
button. You will now see that the icon
for your former text document has changed. It will now be the icon for your default web browser (IE, in our
case). Double-click on the icon to open
it, and you will see a Web page with your “Hello World!” message displayed.
You only need to go through the
above process once. After you have
opened your web page with your message, all
you need now do is go to the menu bar on the browser, select View, then
Source. You will now have another
window open which is a text editor (actually the same one you started
with). Your browser window is still open. Now, adjust both windows so you can view
both at the same time. Try the text
editor on the left with the browser on the right. Now enter some new text into the text editor. Then go through the following sequence:
· File, Save on the Text Editor Menu
· Refresh button on the Browser.
You will now see the results of your
new text on the browser. You can repeat
this process as many times as you wish.
Just remember that anytime you change text in the text editor, you must
go through the above sequence to see the results in the browser. At this point, you can see what a powerful
learning environment is at hand for you and your students.
4. Your First
JavaScript Program - Using the Document Object to Change the Browser’s
Properties
In your text editor that you opened
through your browser, type the following text exactly as shown below:
<script>
document.write(“Welcome
to JavaScript!”);
</script>
Next,
be sure to go through the File, Save sequence on the text editor, and then
click the Refresh button on the browser.
You will now see the following on the browser:
Welcome to
JavaScript!
Here is what has happened.
The <script> tag tells the browser to expect a script language and
not HTML. The <document.write> is
a method of the document object (the “write” method). Note the use of the dot notation, where there is a “.” between
the object (document in this case) and the method (write in this case). The (“Welcome to JavaScript!”) is the
argument passed on to the document object’s write method, so it will know what
to write. In our case it writes Welcome
to JavaScript!. The semicolon tells the
browser that this is the end of a programming statement.
Next, go back to the text editor
adding a new line so that your code is exactly as shown below:
<script>
document.write(“Welcome
to JavaScript!”);
document.bgColor = “red”;
</script>
Pay
attention to upper case and lower case, JavaScript, like C and C++ is case
sensitive. Now go through the File,
Save, Refresh sequence. Your browser
will display the same text as before, but this time its background color is
red. What you have done here is to
change a property of the document
object. Again note the use of the dot method to tell the browser what property
we want to change (in this case bgColor, which means “backgrondColor). So what has been demonstrated here is that
an object, such as the document object has both methods and properties. That these methods and properties can be
accessed using the dot method to tell the browser which ones we wish to use.
Now let the students have fun trying
different colors for the browser background.
For even more fun, have them enter the following code in their text
editor:
<script>
document.write(“Welcome
to JavaScript!”);
document.bgColor = “red”;
document.fgColor = “yellow”;
</script>
With
this, students can now experiment with different color combinations for the
background color and foreground color properties of the document object.
What Students Have Learned in the
Exercise
·
A computer program
consists of a series of commands.
·
For ease of reading
each command is put on a separate line.
·
Each of these lines
is sometimes referred to as a statement.
·
Indentation is used
to help us read and understand the code.
·
In JavaScript, we use
the semicolon to tell the browser when a statement has ended.
·
The Browser
interprets the JavaScript code and displays the results of its interpretation.
·
An object has both
methods and properties.
·
A method causes
something to happen - Such as displaying text on the browser.
·
A property is some
characteristic of the object - Such as its colors.
·
In JavaScript,
methods and properties of an object are identified through the use of a dot
notation.
·
Generally, a method
requires an argument, so it know what it is suppose to do - Such as: document.write(“Please write this.”); The “Please write this.” Is what the write method is suppose to
write.
·
JavaScript, like some
other higher level programming languages is case sensitive. This means that bgColor is not the same as
bgcolor, or BGColor.
5. An Overview of
Programming Languages
A programming language consists of
rules for creating code which can then be used by the computer to perform some
task. We saw that already in Topic 4: Your First JavaScript Program - Using the
Document Object Model.
What follows is a list of some of
the current programming languages:
A.L.I.C.E , Ada, ANNA, APL , AppleScript , assembly language , BASIC, C , C#, C++ , COBOL, CODASYL , cxml , Delphi, Eiffel , FORTRAN , GW-BASIC , Java , JavaScript , JVM, KLOC , LISP, machine language, microcode , Modula-2, MUMPS , Pascal , Perl , Prolog , Python, QBASIC, query language, Rexx, RPG , Smalltalk, snarf , SQL , Tcl, UML , VBScript, Visual Basic , Visual C++, VXML, WSDL, XSP and more. .
Can you imagine having to take a course in each of the above
languages. It would take over a
lifetime, and in the mean time, new languages would be emerging, and older ones
going out of favor.
However, you may be surprised to
find that all of these different languages use almost the same programming
concepts. What is mostly different
about them is their syntax. The word
syntax refers to the spelling and grammar of a programming language. After all, you must remember that computers
are inflexible machines that understand what you type only if you type it in
the exact form that the computer expects.
This expected form is called the syntax of that language.
Each of the above listed programs
defines its own syntactical rules that control which words the computer
understands, and which combinations of words are meaningful, and what
punctuation is necessary (such as the semicolon
we use at the end of each JavaScript statement).
What you will find is that any
programming language need only do three constructs to solve any programming
problem. The three constructs are:
Sequence:
This simply means that programming statements may be
executed in order, one after the other.
An example in JavaScript would be the program we used in the last
section:
<script>
document.write(“Welcome
to JavaScript!”);
document.bgColor = “red”;
document.fgColor = “yellow”;
</script>
In the above program, each programming
statement is executed through the browser in turn, where document.bgColor = “red”;
is executed after the statement document.write(“Welcome
to JavaScript!”);
And the last
statement to be executed through the browser is: document.fgColor = “yellow”;. This
is an example of a sequence
structure.
An example of a sequence construct
in another programming language, such as C++, would be:
int main()
{
cout << “Testing
1, 2, 3 ”;
cout << “Here
is some more text.”;
}
Here there are two programming
statements, both terminated with the semicolon. What they do is simply output text to the monitor. The syntax is different but the concept is
the same, you would see Testing 1, 2, 3
first, then Here is some more text.
On the monitor screen.
Branching:
The second programming construct is branching. Branching is the process of the computer executing different
lines of code depending on a given condition.
For example, in JavaScript,
different sets of code can be executed on the browser depending on the time of
day on the user’s machine. An example
of such code (you can actually try it yourself, it really works) would be:
<script>
Now = new Date();
Hour = Now.getHours();
if (Hour < 12)
document.write("Good morning!");
if (Hour >= 12)
document.write("Morning is gone!");
</script>
In
the above lines of code:
Now = new Date();
Sets the variable Now as a
JavaScript Date method (we know it is a method because of the use of the
parenthesizes following the object Date).
The Date object is one of JavaScripts many built in objects. The next line of code:
Hour
= Now.getHours();
Has
the variable Hour execute the getHours() method of the newly created Now
object. The variable Hour will contain
the hour value of the user’s machine. JavaScript uses military time.
That means 1:00 PM is equal to 13, 6:00 PM is equal to 18. The next line of code:
if (Hour < 12)
document.write("Good morning!");
These
two lines can actually be thought of as one statement (they are broken into two
lines, and indented in such a way as to make them easy to read). Here we see a condition: if (Hour < 12). This means if the time on the user’s machine is less then (<)
12, then execute the next statement. If
the hour is not less than 12, then the next statement will not be displayed. Note that you can test this on your computer
by resetting its time from AM to PM and back again. The purpose of next statement should now be obvious:
if (Hour >= 12)
document.write("Morning is gone!");
Simply
put, the condition being tested here is if the number contained in the variable
Hour is greater than or equal to 12 (>=).
If this condition is true, then Morning
is gone! Will be displayed on the
browser. The above program could have
also been written as follows:
<script>
Now = new Date();
Hour = Now.getHours();
if (Hour < 12)
document.write("Good morning!")
else
document.write("Morning is gone!");
</script>
It should be pointed out that the above if-else syntax is
consistent through most other programming languages.
Iteration:
In programming, the iteration
construct may cause the computer to go back and execute the same section of
code over again and even many, many times over again, depending on a given set
of conditions. For example, you could
write a JavaScript program that would allow a user to order pizzas through
their browser. The program could first
ask how many pizzas the person wanted to order. If the user entered the number 5 for the number of pizzas, then
the program would ask the same set of questions five times. That is, what size pizza, what toppings, and
the like. The way this is done is that
there is only one set of questions in the code. However, in this case this set of questions would be displayed
five times.
An example of iteration in
JavaScript is shown below:
<script>
do
selection = confirm("Do you want to
see this dialog box again?");
while (selection == true);
document.write("Thanks for trying
my program.");
</script>
Again, you can try this JavaScript
code and it will really work. Here is
the loop. It is contained between the do
and the while statements. What
will happen here is that the statement:
selection
= confirm("Do you want to see this dialog box again?");
Will be executed over and over again
as long as the program user selects the OK button on the resulting dialog
box. If they select Cancel on the
resulting dialog box, then the statement:
“Thanks for trying my program”
will be displayed on the browser and the program will terminate.
Note the use of the double equals
sign in (selection == true). The ==
means “equal to” in JavaScript. This is
the same thing it means in C, C++, C# and Java.
Well that is it. Those are the three programming constructs
that any programming language needs to solve any programming problem: sequence,
branching, and iteration. All higher level
languages can use these constructs to solve programming problems. All that is needed now is for the student to
know when to use them. Once they
understand that, then they can use those constructs to solve the same problems
in any programming language.
What Students Have Learned in the
Exercise
·
Definition of a
Programming Language
·
An appreciation of
the number of programming languages in use today.
·
The concept that most
of the popular programming languages have more in common with each other than
differences.
·
The main difference
between the popular programming languages is their syntax, not their
constructs.
·
The definition of
syntax.
·
There are only three
programming constructs needed to solve any programming problem.
·
All of the popular
programming languages use these constructs, only the syntax is different.
·
The constructs
are: Sequence, Branching, and
Iteration.
·
The Sequence
construct is the process of having one computer statement executed after the
other in the order they are written.
·
The Branching
construct is the process of executing a given set of code depending on a
condition.
·
The Iteration
construct may cause the execution of a set of program code more than once
depending on a condition or set of conditions.
·
Branching constructs
use an if-else syntax.
·
Iteration constructs
may use a do-while syntax.
6. Variables and
Their Use
Think of a variable as a word that
can contain a value. For example:
<script>
var MyWord = “Hello there!”;
document.write(MyWord);
</script>
When the above code is executed, the
output on the browser will be:
Hello there!
Note that the identifier MyWord was proceeded by the
JavaScript term var. This tells
JavaScript that MyWord is to be a variable.
In the next line of code, we assign
a value to the variable. The = symbol
is used for assignment (it does not mean equal, it means assign). The value assigned to the variable is the string “Hello there!”. Note
that the string is enclosed in quotation marks. The quotation marks are used so that JavaScript does not think
that the words Hello and there! are variables.
The last line of code, the
document.write(MyWord); tells JavaScript to display the contents of the
variable MyWord. Note that MyWord was
not enclosed in quotation marks because we want JavaScript to treat it as a variable
not as a string. If we had done:
document.write(“MyWord”);
Then the output on the browser would
have been:
MyWord
Which is not what we wanted.
A good first application of
variables is the foreground and background color program introduced as one of
the first JavaScript programs:
<script>
document.bgColor = “red”;
document.fgColor = “yellow”;
document.write(“The background color is
red. “);
document.write(“The foreground color is
yellow.”);
</script>
Have students experiment with
different color combinations, but require that if they change any color in the
document color properties, they must also change the stated color in the
document.write() method. Doing this,
they see that they must make two program changes for each color change. This not only takes longer but it is prone
to error. Consider the following code:
<script>
document.bgColor = “salmon”;
document.fgColor = “tan”;
document.write(“The background color is
somon. “);
document.write(“The foreground color is
dan”);
</script>
An easy way of overcoming these
problems is through the use of variables.
This is demonstrated in the following program:
<script>
var MyBGColor = “salmon”;
var MyFGColor = “tan”;
document.bgColor = MyBGColor;
document.fgColor = MyFGColor
document.write(“The background color is
“ + MyBGColor);
document.write(“The foreground color is
“ + MYFGColor);
</script>
Now, to change a color, the student
need only change the variable assignment in one place. The resulting color assignment will now
affect two places in the program. Note
the use of quotes and the + sign in the document.write() method. The + sign means to append. So the string “The background color is “ is
appended to the value of the variable
MYBGColor. Note that MYBGColor was not
put in quotes because we want to display the value it contains.
Again, have the students experiment
with the above program by changing the colors of the background and the
foreground. Ask what would the output
be if the variable MyBGColor were put inside quotes in the document.write()
method.
What Students Have Learned in the
Exercise
·
A variable may be
thought of a word that can contain a value.
·
The word used for the
variable is called an identifier.
·
The = symbol means assignment, not equal.
·
Strings are enclosed
within quotations marks so they are not mistaken for variables.
·
A variable identifier
is not enclosed within quotation
markes.
·
One of the advantages
of using variables is it helps prevent program errors and reduces the amount of
code changes. This was illustrated in the color changing program posted in this
section.
7. Rules for
Creating Variables
All of the popular higher level programming languages use
variables. They all have rules for
creating identifiers for variables.
Basically the rules are the same.
So what you learn here, will apply equally well to these other
languages.
What follows, may not be a
programming requirement for the program to work properly, however it does
reflect the good programming practices used in programming.
·
Always declare
variables before using them. In
JavaScript you do this by using the keyword:
var Example:
var MyNumber;
·
As in C, C++, C#, and
Java, variables are case sensitive.
This means that the following statements declare two different
variables:
var MyNumber;
var mynumber;
·
Variable names may be
of any length, but should be a descriptive term that helps identify the purpose
of the variable. As an example, if a
variable is to hold the value of a total cost, it would make sense to use the
following variable declaration:
var TotalCost;
·
The first character
of a variable must be an ASCII letter (either upper or lowercase), or an
underscore (_). This means that a
number (1, 2, etc.) cannot be used as the first
character. Subsequent characters must
be letters, numbers, or underscores. As
an example, the following are legal variable identifiers:
var MyBestEverVariable;
var Number_2;
var _MYCONSTANT;
var Total_Cost_3;
var RU_4Me;
·
The identifier cannot
be a program reserved word, such as var. These are the words which tell the
program what to do. In JScript, the
reserved words are:
·
break
·
delete
·
function
·
return
·
typeof
·
case
·
do
·
if
·
switch
·
var
·
catch
·
else
·
in
·
this
·
void
·
continue
·
false
·
instanceof
·
throw
·
while
·
debugger
·
finally
·
new
·
true
·
with
·
default
·
for
·
null
·
try
Each of the above words, are
reserved for the program commands. Many
of the above list of reserved words are identical to those used in other
high-level programming languages.
·
Future reserved words
for JScript are:
·
abstract
·
double
·
goto
·
native
·
static
·
boolean
·
enum
·
implements
·
package
·
super
·
byte
·
export
·
import
·
private
·
synchronized
·
char
·
extends
·
int
·
protected
·
throws
·
class
·
final
·
interface
·
public
·
transient
·
const
·
float
·
long
·
short
·
volatile
At this point it you should present
a list of identifiers that are legal and those that are not to the
students. Give them practice in making
up their own variable identifiers and have the class decide if they are legal
or not.
What Students Have Learned in the
Exercise
·
All of the popular
higher level languages use variables.
·
The rules for using
variables are consistant among these languages.
·
A variable identifier
is the word used to be the variable.
·
Good programming
practice requires that you should declare a variable identifier before using
it.
·
In JavaScript
variables are case sensitive. This is
also true for C, C++, C#, and Java.
·
Variables may be of
any length, but should be descriptive of the values they will hold.
·
The first character
of a variable must ben an ASCII letter (upper or lower case) or the underscore.
·
The first character
of a variable cannot be a number.
·
No spaces are allowed
in variables.
·
Other variable
characters, after the first, may be letters, numbers, or underscores.
·
A variable identifier
cannot be a program reserved word.
8. The
Input-Process-Output Model
The Input-Process-Output Model is commonly used in
programming. Basically a program
written with this model requires some external source of information, takes
that information a processes it in some way, then outputs the result for
someone to see and/or storing the results for further use.
A common example of this model is
when a program user is using a
program written by a programmer.
Generally, the program user does not need to know anything about
programming to use the program written by a programmer. Programmers, those who create the program,
should develop the program in such a way that the users of these programs do
not need to know programming techniques to use the program.
In a more specific example, we will
develop a program which asks the program user to enter the color they wish to
have as a background color for their browser.
This will be developed in such a way that the user only needs to
interact with the browser and not with the program code developed by the
programmer.
Here is the program:
<script>
var BGColor;
BGColor = prompt("Enter the background
color you want: ", "");
document.bgColor = BGColor;
document.write("The background color
you selected is: " + BGColor);
</script>
To
best describe the Input-Process-Output model is to actually try the program in
the browser. When the program is
executed, the user will see a dialog box asking the to type in a color for the
background. This dialog box represents
the Input part of the
Input-Process-Output model. Once the
user types in a color and presses the OK button on the dialog box, the Process part of the Input-Process-Output
model takes place. In the Process part, the color entered by the
user is processed along with the other commands by the browser. The third and last part of the
Input-Process-Output model then takes place when the user actually sees the
results of the selected background color on their browser - This is the Output part.
In
analyzing the above program we have:
var
BGColor;
This
is where the variable which will hold the value of the color entered by the
user is declared. Note that the
variable identifier meets all of the legal requirements of variables. The next line of code:
BGColor
= prompt("Enter the background color you want: ", "");
This
line of code causes a dialog box to be displayed over the browser. Whatever word the user had typed into the
text box when the OK button is pressed will now be assigned to the previously
declared identifier BGColor. In the
next line of code:
document.bgColor
= BGColor;
In
the above line of code, the value stored in the variable identifier BGColor is
now assigned to the background color property of the document object. This will then be processed by the browser
to produce the resulting background color.
The next line of code:
document.write("The background color
you selected is: " + BGColor);
In the above line of code the
document.write() method is evoked and the argument string “The background color
you selected is: “ is appended with the value of the variable identifier
BGColor.
What you have seen is an example of
the Input-Process-Output model used in programming. Some examples of these models would be programs that would do the
following:
·
Get a users name and
then return a greeting on the browser using that name.
·
Ask the user what
color text they would like to see.
·
Ask the user what
color text and background they would like to see the browser display. (This requires two separate inputs).
·
Ask the user their
name and favorite color and then have their name displayed on the browser in
that color.
The
programming process for developing the Input-Process-Output model is standard
for programming languages. It basically
requires the programmer to answer three questions:
1. What is/are the input(s).
2. What is/are the process(es).
3. What is/are the output(s).
However, the most important
question, in addition to the above three, that the programmer must answer
is: What
are the program requirements? This
is generally referred to as the problem statement or the programming
requirement.
As
an example, let’s look at the background color change program again, and go
through this three-step development process.
First, let’s state the programming requirement:
“Create
a program that will allow the user to change the background color of the
browser.”
When developing such programming
requirements, it is understood, that the user will not interact with the
program code.
We can now do the first phase of
program development. This is done by
actually stating the programming requirement in our program. This is done through the use of program comments. A program comment is there just for the programmer and has no
affect on the program itself. Each line
of a program comment must begin with the // (double forward slash symbol used
twice). As an example:
// This is a comment.
Will not cause any process to take
place when the program is executed. For
multiple lines of comments, you may use:
// Here is my first comment.
// This is my second comment.
//
Now my last comment.
For multiple line comments, you may
also use the /* and */ at the
beginning and the ending of the comment lines.
As an example:
/*
Here is my first comment.
This is my second comment.
Now my last comment. */
So we will always start every
program we develop, no matter what programming language we are using with a
comment. And this comment will be the Programming Requirement. You may use any of the above comment forms
(that is the // or the /* and */).
However, whichever one you choose should be consistent throughout the
program. This is done by giving the
program a name and stating what the
program does as if the program had already been completed. It is also nice to put your name down as the
programmer.
/************************************************/
/* Background Color Changer */
/************************************************/
/* By: A. G. Programmer */
/************************************************/
/* This program allows the user to */
/* change the background color of the */
/* browser. */
/***********************************************/
What you have now completed is
referred to as the programmer’s block. The programmer’s block is a block of
commented code that the programmer writes just for himself. It describes important features of the
program and serves as an aid to the programmer to help define various parts of
the program.
You can now actually run this
program through the browser. Nothing
will happen, but at least you have documented for yourself, the programmer,
what your program is supposed to do. By
the way, the above code is identical to what you could use in C, C++, Java, and
C#.
The next step is to define, through
the use of comments, the Input code, the Process code and the Output code. This is done as show below:
/************************************************/
/* Background Color Changer */
/************************************************/
/* By: A. G. Programmer */
/************************************************/
/* This program allows the user to */
/* change the background color of the */
/* browser. */
/***********************************************/
/* Input: */
/* Process */
/* Output */
Next, we need to state how we plan
to implement each part:
/************************************************/
/* Background Color Changer */
/************************************************/
/* By: A. G. Programmer */
/************************************************/
/* This program allows the user to */
/* change the background color of the */
/* browser. */
/***********************************************/
/* Input: Get the background color from the user. */
/* Process: Set the user color to the background
color of the
browser. */
/* Output: Tell the user what color they entered. */
The next item is to decide if
variable identifiers are needed. We see
that there is one and only one item we are dealing with here. A variable is generally needed for every noun
used in the problem statement. We see,
in this case, the user and the background. In this case the only one we need be concerned about is the
background color. So we need to create a variable for the
background color. It is good
programming practice to place a comment after each declared variable that
explains the purpose of the variable as follows:
/************************************************/
/* Background Color Changer */
/************************************************/
/* By: A. G. Programmer */
/************************************************/
/* This program allows the user to */
/* change the background color of the */
/* browser. */
/***********************************************/
var BGColor; //The background color entered by the user.
/* Input: Get the background color from the user. */
/* Process: Set the user color to the background
color of the
browser. */
/* Output: Tell the user what color they entered. */
Note that we have finally entered
our first line of executable code! This
is done only after we have clearly stated
what the program will do and broken it down into its component parts.
Every time a new line of code is
added, the program should be tested for errors. Otherwise, if the program is first tested after many lines of
code, it may be more difficult to discover the problem
Next, Input code is developed:
/************************************************/
/* Background Color Changer */
/************************************************/
/* By: A. G. Programmer */
/************************************************/
/* This program allows the user to */
/* change the background color of the */
/* browser. */
/***********************************************/
var BGColor; //The background color entered by the user.
/* Input: Get the background color from the user. */
BGColor = prompt(“Enter
the background color: “, “”);
/* Process: Set the user color to the background
color of the
browser. */
/* Output: Tell the user what color they entered. */
Another line of code has been added,
so test the program again. This time a
dialog box should appear asking the user to enter the background color. If there is a problem here, then the problem
has to be with the new line of code we just added, and not anything else in the
program.
Now we add the Process code:
/************************************************/
/* Background Color Changer */
/************************************************/
/* By: A. G. Programmer */
/************************************************/
/* This program allows the user to */
/* change the background color of the */
/* browser. */
/***********************************************/
var BGColor;
//The background color entered by the user.
/* Input: Get the background color from the user. */
BGColor = (“Enter the
background color: “, “”);
/* Process: Set the user color to the background
color of the
browser. */
document.bgColor =
BGColor;
/* Output: Tell the user what color they entered. */
We now test the program again. If there is a problem, it has to be with the
last line of code we entered and nothing else in the program.
Next we enter the Output code:
/************************************************/
/* Background Color Changer */
/************************************************/
/* By: A. G. Programmer */
/************************************************/
/* This program allows the user to */
/* change the background color of the */
/* browser. */
/***********************************************/
var BGColor; //The background color entered by the user.
/* Input: Get the background color from the user. */
BGColor = (“Enter the
background color: “, “”);
/* Process: Set the user color to the background
color of the
browser. */
document.bgColor =
BGColor
/* Output: Tell the user what color they entered. */
document.write(“The
color you selected is: “ + BGColor);
Test the program again. If everything now works, the make a backup copy and give it a version
number. For example. If you named this program:
BGChanger.htm
The backup copy should be:
BGChanger_v1.htm
If you now need to later modify the
BGChanger.htm program, to say also ask the user for their name and then display
their name along with the color they choose, you would leave the copy of
version one as is, make the changes in BGChanger.htm, then make another backup
copy and save it as version 2. You
would now have three programs as shown:
BGChanger.htm
BGChanger_V1.htm
BGChanger_v2.htm
Doing the above is considered good programming practice. It also can save you programming time, just
in case you need to refer to earlier versions of your program.
At this point, it would be helpful
to reinforce these concepts and get the student into good programming practices
methods by assigning several Input-Process-Output models. First require that they can enter all of the
required comments and break the program down into its component parts. Have them first show they are capable of
doing this before they enter any executable code. Once you have seen what they have done, then ask them to do the
next step, which is to identify and comment on all required variables. Again, observe this step before any
executable code is entered. As a last
step, have them enter executable code for each section, one statement at a
time, making sure they test each new line
of code entered before going on to the next line. If a student runs into problems, all you nee do then do is
ask: “What was the last line of code
you entered that worked?” Using this
method can save you and the student hours of program debugging time.
The table below summarizes the Program
Development Process:
|
Step |
Activity |
|
1 |
Develop the Programmer’s Block. Name the program, and describe what the
program will do. |
|
2 |
Break the program into parts. Create space for the Input code, Process
code, and Output code. |
|
3 |
Explain how each of the above parts will
be accomplished. |
|
4 |
Declare all variables needed by the
program. |
|
5 |
Start developing code for each of the above
parts. This should be done one
statement at a time where each new statement is tested before the next line
of code is entered. |
It is important that you require all
of your students to conform to the above Program Development Process. Understandably students may be anxious to
write code as quickly as possible just to “get the program working”. However, doing this leads to bad programming
habits and frustration on the student’s part as well as that of the
teacher. By using the Program
Development Process as outlined above, program errors should be limited to just
one line of code. It not, at this
stage, then the student has not been following the correct programming process.
What Students Have Learned in the
Exercise
·
The structure of the
Input-Process-Output Model
·
Difference between
the Programmer and the Program User.
·
Programming examples
of the Input-Process-Output Model.
·
The use of comments.
·
Development of the
Programming Requirement.
·
Requirements of the
Programmer’s Block.
·
Breaking a
programming problem into component parts.
·
Developing program
code after the program has been
designed.
·
Backing-up programs
and the use of program versions.
·
The steps required in
the Program Development Process.
9. Program
Development with Functions
We saw in the last section, the
breaking down of a programming problem into smaller parts and then the
development of each of these parts.
Though the programming problem we had was simple, the process
illustrated is used in all larger and more complex programs. There are several reasons for doing
this. First, breaking a complex problem
down into smaller steps is a time-tested method for successful problem solving
used in almost every branch of science and technology. Second, working on small sections of a
program can reduce programming errors and is easier to correct them when they
may occur. Third, programs developed in
parts are easy to modify and update.
One last reason is that large professional programs are developed by a
team of programmers. Breaking up a
program into smaller component parts allows each programmer to work on a
separate part of the program without having to wait for other programmers to
start or finish their parts.
The following is a JavaScript
function:
<script>
function MyFunction( )
{
document.write(“This
is from MyFunction. <br>”);
document.write(“This
is also from MyFunction.”);
}
</script>
If you try the above in your
browser, nothing will happened because the function has not been called.
We will discuss more of that later, but for now, lets look at the
important parts of a function.
The first thing to notice is the use
of the keyword function. All JavaScript functions start with this
reserved word. The second thing to see
is that there is a space after function
and then a name assigned to the
function. In our case the name is
MyFunction. The names of functions obey
the same rules as the names we choose for variable identifiers. Immediately following the function name is a
set of parenthesis ( ). These must
appear right after every function name.
The next item to observe is that there is not a semicolon (;)
following the parenthesis.
On the next line we see the opening
brace {. This represents the beginning of the body of the function. The
end of the body of the function (and the function itself) is represented by the
closing brace }. You may put as many statements within a
function as you choose between the opening and closing braces of a
function. By the way, what was said
here about the syntax of creating a function is almost identical to that of
creating a function in C, C++, C#, and Java.
To call a function (make it
execute), you only need to enter the name of the function followed by the
parenthesizes. This is shown below:
<script>
MyFunction( );
//This calls the following function.
function MyFunction( )
{
document.write(“This
is from MyFunction. <br>”);
document.write(“This
is also from MyFunction.”);
}
</script>
You can now try the above program in
your IE5 browser. Note that there is a
semicolon after the called function. It
is used here because calling a function represents a program statement. Note, and this is important, that when
calling a function, you must have the parenthesizes. If you do not, the program will think you are using a variable
identifier and not calling a function!
One of the main uses of functions is to break a program down
into its component parts. We did this
in the last section through the use of comments. From now on, we will do this through the use of functions.
As an example, let’s say we had a
programming problem that we could break down into four parts. The program below illustrates the approach
to be used in designing such a program:
<script>
main( );
function main( )
{
explain_program( );
get_input( );
process_it( );
show_results( );
}
</script>
As you can see from the above
program, the function main() simply calls all of the functions used in the
program. The idea of doing this is that
just by looking at the functions called by main() any programmer can quickly
see what the program is expected to do without having to look a lot of complex
code first. We do need to define each
of the called functions for the program to work, and that is what we will do
next:
<script>
main( ); //Calls function main( )
function main( )
{
explain_program( );
get_input( );
process_it( );
show_results( );
}
function explain_program( )
//Explains what the program will do.
{
document.write(“From
explain_program. <br>”);
}
function get_input( ) //Gets input from the program user.
{
document.write(“From
get_input. <br>”);
}
function process_it( ) //Processes
the input from the program user.
{
document.write(“From
process_it. <br>”);
}
function show_results( ) //Displays
the results to the program user.
{
document.write(“From show_results. <br>”);
}
</script>
When executed through the browser,
the output will be:
From explain_program.
From
get_input.
From
process_it.
From
show_results.
From this point forward, all programs we develop will be
developed in this fashion.
What has been done here is to break
up the program into component parts and through the use of the document.write(
) method, verify that each part has been called in the correct order from our
function main( ).
We
will now go through the steps of developing a program from a problem statement
using separate functions for each part of the program. The problem statement will be kept simple so
students may focus on the problem solving process
and not the code necessary to solve
the problem.
A
pizza company wants you to create a program for them that will compute the
total cost of a pizza order. Since they
are a new company, they make only one kind of pizza which cost $8.00 each. They want the program user to be able to
enter how many pizzas they wish to order and then the total amount of the order
will be displayed.
The
first step is to create the beginning of the programmer’s block. This will include giving the program a name,
putting in your name as a programmer and then stating what the program will do:
<script>
/********************************************/
/*
Pizza Cost Calculator
*/
/*********************************************/
/*
Developed by: A. G. Programmer */
/********************************************/
/*
This program will get the number
*/
/* of
pizzas ordered and compute the */
/*
total cost of the order. There
is */
/* only one kind of pizza to order. */
/*********************************************/
</script>
Save
the above program and test it. Nothing
should happen, but, of an error is indicated, this is the time to fix it.
The
next step is to try and solve the problem by hand. If you don’t know how to solve the problem at this stage,
entering program code is not going to help, it will just make things
worse. So here we go:
Total
Cost = (Number of pizzas ordered) X (Cost of each pizza)
So
if you ordered 5 pizzas at $8.00 each:
Total
Cost = 5 X $8.00
Total
Cost = $40.00
Save
the above results so that when you try the program you can check it’s answer
against yours.
From
the above we can see that our program will consist of three major parts:
1. Get how many pizzas are to be ordered.
2. Compute the total cost.
3. Display the total cost.
We can now add the above to the
programmer’s block in the form of functions.
We do this as follows:
<script>
/********************************************/
/*
Pizza Cost Calculator
*/
/*********************************************/
/*
Developed by: A. G.
Programmer */
/********************************************/
/*
This program will get the number
*/
/* of
pizzas ordered and compute the */
/*
total cost of the order. There
is */
/* only one kind of pizza to order. */
/*********************************************/
/* Functions Used */
/*------------------------------------------------*/
/* Get_Order( ) */
/* Gets the total number of pizzas */
/* from the program user. */
/*-----------------------------------------------*/
/* Compute_Total( ) */
/* Computes the total cost of the */
/*
pizza order.
*/
/*----------------------------------------------*/
/*
Display_Total( )
*/
/* Displays the total cost of the */
/*
order to the program user. */
/******************************************/
/* Variables Used */
/*---------------------------------------------*/
/* Number_Ordered */
/* The number of pizzas ordered */
/*
by the program user.
*/
/*---------------------------------------------*/
/* Total_Cost */
/* The total cost of the pizza order. */
/******************************************/
</script>
Once
the above is completed, the student should save it and try it to insure there
are no errors to this point. What is
now in the above programmer’s block is a clear statement of the problem and
exactly how the student proposes to solve the problem. Note that at this point not one line of executable code has been written. It is important that you have the student
show the completed programmer’s block to you before any executable code is entered. Doing this insures that each student will go through the above
problem solving process where the focus is to be on developing the problem
solving skills required in every programming language implementation.
The next step is to develop the
main( ) function and to declare the variables and constants (this follows the
programmer’s block):
main( ); //Calls function main(
)
var Number_Ordered; //Number of pizzas ordered.
var Total_Cost; //Total cost of the order.
function main( )
{
Get_Order( );
Compute_Total( );
Display_Total( );
}
function
Get_Order( )
{
document.write(“From Get_Order(
) <br>”);
}
function Compute_Total( )
{
document.write(“From
Compute_Total( ) <br>”);
}
function Display_Total( )
{
document.write(“From
Display_Total( ) <br>”);
}
</script>
The
above program should now be saved and tested.
If there are any errors encountered here, now is the time to fix
them. The output on the browser should
be:
From
Get_Order( )
From Compute_Total( )
From Display_Total( )
You
should have each student demonstrate the resulting output to you. Doing this makes everyone aware of the
correct programming sequence. What the
student has done here is to create function
stubs. A function stub is the
function declaration without any executable code in the body, except for an
output statement to verify that the function is properly called by main(
). This process will be even more
important when branching and iteration are later introduced.
The
next step is to code one function at a
time and test it. Remember to have
students test each new line of code they enter before going to another line of
code! Doing this will save both you and
the student hours and hours of program debugging.
The
completed program is shown below:
<script>
/********************************************/
/*
Pizza Cost Calculator
*/
/*********************************************/
/*
Developed by: A. G.
Programmer */
/********************************************/
/*
This program will get the number
*/
/* of
pizzas ordered and compute the */
/*
total cost of the order. There
is */
/* only one kind of pizza to order. */
/*********************************************/
/* Functions Used */
/*------------------------------------------------*/
/* Get_Order( ) */
/* Gets the total number of pizzas */
/* from the program user. */
/*-----------------------------------------------*/
/* Compute_Total( ) */
/* Computes the total cost of the */
/*
pizza order. */
/*----------------------------------------------*/
/*
Display_Total( )
*/
/* Displays the total cost of the */
/*
order to the program user. */
/******************************************/
/* Variables Used */
/*---------------------------------------------*/
/* Number_Ordered */
/* The number of pizzas ordered */
/*
by the program user.
*/
/*---------------------------------------------*/
/* Total_Cost */
/* The total cost of the pizza order. */
/******************************************/
main( ); //Calls function main( )
var Number_Ordered; //Number of pizzas ordered.
var Total_Cost; //Total cost of the order.
function main( )
{
Get_Order( );
Compute_Total( );
Display_Total( );
}
function
Get_Order( )
{
//document.write(“From Get_Order( ) <br>”);
Number_Ordered = prompt(“How
many pizzas? “, “”);
}
function Compute_Total( )
{
//document.write(“From
Compute_Total( ) <br>”);
Total_Cost = Number_Ordered *
8; //8 is total cost of each pizza.
}
function Display_Total( )
{
//document.write(“From
Display_Total( ) <br>”);
document.write(“Total cost
of order is: $” + Total_Cost);
}
</script>
Note
that the document.write( ) methods for verifying the calling of the function
from main( ) have simply been commented out.
This is good programming practice, just in case you need to again verify
the actual program sequence. We now
only need to make a few changes to our Program Development Process. It is important to make sure that each
student have a copy of this table on or near their computer and that they can,
at all times, demonstrate to you that they are following this process.
Program Development Process:
|
Step |
Activity |
|
1 |
Develop the Programmer’s Block. Name the program, and describe what the
program will do. |
|
2 |
Solve the problem by hand. If you can’t writing code isn’t going to
help. |
|
3 |
Break the program into functional
parts. In the Programmer’s Block
identify each of the functions you intend to use and what each of them will
do. |
|
4 |
Identify and define all of the program
variables you intend to use. Do this
only as comments in the Programmer’s Block. |
|
5 |
Call and write function main() which will
call all of the functions used in your program. Use only function stubs to test if your functions are in the
correct calling order. |
|
6 |
Start developing code for each of the
functions. This should be done one
statement at a time where each new statement is tested before the next line
of code is entered. |
What Students Have Learned in the
Exercise
·
The syntax required
for a user defined function.
·
How to call a function.
·
How to create a main(
) function which can call other functions.
·
How to use a main( )
function to help break a programming problem into smaller parts using
functions.
·
Expanding the
Programmer’s Block to include the description of each function we propose to
use in the program and its purpose.
·
Using the
Programmer’s Block to give a description of each variable we propose to use in
the program and its putpose.
·
Using function stubs
with the document.write( ) method to verify the calling order of each function.
·
The Program
Development Process using functions.
10. Program
Development with Structures
A structure is a programming method for storing a collection of
related data. For example, your check
book contains checks which all have related data. The data on a check we
will consider here are:
·
Number
·
Date
·
Payee
·
Amount
An example of a structure is as
follows:
<script>
function MyChecks( )
{
self.number;
self.date;
self.payee;
self.amount;
}
</script>
From the above program, note the use
of the reserved word selt. In the above example, self refers to the
function in which each of the data are contained. Each of these data are called structure
members. For example:
self.number;
is a member. So, for the above structure definition, we
have four members:
self.number;
self.date;
self.payee;
self.amount;
Once the structure is defined, you
can declare a new identifier which will have the same structure with the same
related data. To do this, the keyword new is used:
<script>
function MyChecks( )
{
self.number;
self.date;
self.payee;
self.amount;
}
_101 = new MyChecks( );
</script>
The structure identifier used here
is _101. This obeys the rules for any identifier. Recall that you can not start with a number,
but you may start with the underscore.
What we are going to do here is to assign values to each of the members
for check 101.
<script>
function MyChecks( )
{
self.number;
self.date;
self.payee;
self.amount;
}
_101 = new MyChecks( );
_101.number = 101;
_101.date =
“10/12/02”;
_101.payee = “Tom Smith”;
_101.amount = 12.45;
</script>
Note the use of the dot notation to
identify each structure member. If you
had only one check to keep track of, using a structure would not make any
sense. However, if you have many items,
like a check, all of which share related data, then using a structure does make
sense. For example, here are some more
checks with values assigned to each of their members:
_102 = new MyChecks();
_102.number = 102;
_102.date
= "10/25/02";
_102.payee
= "Mary Jones";
_102.amount
= 75.24;
_103 = new MyChecks();
_103.number = 103;
_103.date = "11/05/02";
_103.payee = "John
Johnson";
_103.amount = 103.15;
Now, to see the information for any
one check you can use the document.write( ) method as follows:
document.write(“Number: “ +
_102.number + “<br>”);
document.write(“Date: “ + _102.date
+ “<br>”);
document.write(“Payee: “ +
_102.payee + “<br>”);
document.write(“Amount: “ +
_102.amount);
The output on the browser would then
present information about check number 102:
Number:
102
Date: 10/25/02;
Payee: Mary Jones
Amount:
75.24
A more efficient way of doing the
above is to use the keyword with. The with
instructs the program to use the structure identifier with each member. This is done as follows:
with(_102)
{
document.write(“Number: “ + number +
“<br>”);
document.write(“Date: “ + date +
“<br>”);
document.write(“Payee: “ + payee +
“<br>”);
document.write(“Amount: “ +
amount);
}
The output will now be the same as
before. However, to find the data for a
different check number, you need only change the argument of the with statement. Note the use of the braces. The braces tell the with to treat all of the document.write( ) methods as belonging to
the with(_102). Note also, that there is now semicolon after
the with. The reason for this is that with(_102)
is not a complete statement, it must have other information following it.
The completed program is shown
below:
<script>
function MyChecks()
{
self.number;
self.date;
self.payee;
self.amount;
}
_101 = new MyChecks();
_101.number = 101;
_101.date = "10/23/02";
_101.payee = "Tom Smith";
_101.amount = 12.43;
_102 = new MyChecks();
_102.number = 102;
_102.date = "10/25/02";
_102.payee = "Mary Jones";
_102.amount = 75.24;
_103 = new MyChecks()
_103.number = 103;
_103.date = "11/05/02";
_103.payee = "John Johnson";
_103.amount = 103.15;
with (_102)
{ document.write("Number: " +
number + "<br>");
document.write("Date: " + date +
"<br>");
document.write("Payee: " + payee
+ "<br>");
document.write("Amount: " + amount
+ "<br>");
}
</script>
What Students Have Learned in the
Exercise
·
A structure is a programming method for
storing a collection of related data.
·
How a structure is
defined.
·
The use of the dot
notation to identify structure members.
·
Creating an
identifier to represent a structure.
·
Use of the new keyword.
·
Using the dot
notation to separate the structure identifier from the structure member.
·
Assigning values to
structures.
·
Displaying structure
member values.
·
Using the with keyword to work with structure members.
11. Creating
and Using Data Files
In
the last section, you saw how to use a structure
as a way of organizing related data.
You also say how to enter and view data from a structure. In the example used in the last section,
data was entered about checks in a check book.
This was done as follows:
_101 = new MyChecks();
_101.number = 101;
_101.date = "10/23/02";
_101.payee = "Tom Smith";
_101.amount = 12.43;
Data for each individual check was
entered as a part of our main program.
This worked fine in our example where we were entering data for just
three checks. Consider, however, if
there were hundreds of checks for which data were to be entered. Having all of this in our main program would
make for a very large program. When
there are large amounts of data, that data should be stored in its own file,
separate from the program that will operate on that data. T
In this section, we will store the
check data structure and the data for separate checks in a separate file and
then simply use our program to display the information of any single check we
choose.
To test this out, use the following
simple case to demonstrate how JavaScript can process data from a separate
file. Keep in mind that since
JavaScript is a scripting language,
all of its elements are written in text.
The first thing to do is to create a
new text file. Name it:
data1.txt
Open the data1.txt file and enter
the following (Note, you do not need
the <script></script> tags for this file, you only need to enter
exactly what you see below:
document.write(“From the
data1.txt file.”);
Save the text file.
Now, open a new html document. View the source and enter the following:
<script src = “data1.txt”>
</script>
Do a file save and then refresh the
browser. The output on the browser will
be:
From the data1.txt file.
What has been demonstrated here is
the ability to use a program to get data or program instructions from another
file. This was achieved by the
statement:
<script src = “data1.txt”>
</script>
The src can be thought of as a
command which instructs the browser to look for a file (data1.txt, in our case)
and insert the contents of that file between the <script> and
</script> tags. So, effectively,
what has happened in this case is that the document.write(“From the data1.txt
file.”); was inserted into the html
document and then executed when the browser was refreshed. This is the reason why you do not put
<script> and </script> tags in the text file; because it will be
using the <script> and </script> tags in the html document.
It should not be a big step from
here to realize what we will now do with our check book structure. We will go to our data1.txt file, erase its
old contents and enter the following
(Remember, no <script> </script> tags!):
//My Data1 File
function MyChecks() //Defines the structure.
{
self.number;
self.date;
self.payee;
self.amount; }
//Data Follows:
_101 = new MyChecks();
_101.number = 101;
_101.date = "10/23/02";
_101.payee = "Tom Smith";
_101.amount = 12.43;
_102 = new MyChecks();
_102.number = 102;
_102.date = "10/25/02";
_102.payee = "Mary Jones";
_102.amount = 75.24;
_103 = new MyChecks()
_103.number = 103;
_103.date = "11/05/02";
_103.payee = "John Johnson";
_103.amount = 103.15;
Save the file. Then open the html page you used in the
previous example (the one with the <script src=”data1.txt”>
</script> tags. View the source
and enter the following:
<script src =
"data1.txt"></script>
<script>
with(_101)
{
document.write("<b>Check
Number: </b>" + number + "<br>");
document.write("<b>Check Date:
</b>" + date + "<br>");
document.write("<b>Check
Payee: </b>" + payee + "<br>");
document.write("<b>Check
Amount: </b>$" + amount + "<br>");
}
</script>
Do a file/save and then refresh the
browser. You should see on the
following on the browser:
Check
Number: 101
Check Date: 10/13/02
Check
Payee: Tom Smith
Check
Amount: $12.43
In order to see the data from
another check, you only need to change the check identifier in the with statement.
The ability to “hide” data, as we
did here in another file, is a very powerful concept. To illustrate this, you
may want to have the students create more than one data file. They can then, from their html document,
select which file they want to get their data from. For this check book example, each new data file could represent a
separate check book. This concept will be used again when we discuss abstraction.
What Students Have Learned in the
Exercise
·
The concept of
separating data from a program which uses the data.
·
How to create a text
file which can hold data and the structure definition for that data.
·
How to create a text
file which can hold program commands.
·
Use of the <script
src= “FileName.ext”> </script> tags to bring data from FileName.ext
into the html document between these script tags.
·
The concept that
there can be more then one separate data file used by the calling program to
process the data.
12. Program
Development with Objects
You have been using objects
in many of the exercises presented up to this point. Recall that an object
has two major features. They are properties and methods. Remember that a property is some feature of the object,
while a method actually does
something.
Remember our first object what the document object. We discovered two properties that it had:
document.bgColor
document.fgColor
Recall that we could assign different colors to these
properties. The fist set the foreground
color (in this case, the color of the text).
We also worked with a method for the document object. This
method allowed us to have information appear on the browser:
document.write(“Here is some
text.”);
Recall that the above method for the document object caused
the text in it’s argument to appear
on the browser:
Here is some text.
What is happening with the document
object is it is obeying some structural rules. We didn’t write these rules, someone else did. To further investigate what these rules may look like, compare a property
of the document object to one of our check book structure members:
document.bgColor = “red”;
_101.payee
= “Fred”;
Observe that both of the syntax used (using the dot
notation) are identical. This would
imply that the document object must
have a set of rules which have the same syntax as our structure, which we used for our check book program. You may be surprised to find that this is
indeed the case. Our check book structure had properties (check number, check date, payee, and amount) but it did
not have any methods (the structure
could not cause anything to happen).
We can make a modification on our
check book structure, that will cause
it to do something (like display information on the browser, much in the same
way that the document.write( ) method
displays information). When we modify a
data structure so that it also has methods as well as properties we
then have what is called a class.
You can think of a class as a blueprint for an object.
For example, our check book structure
served as a blueprint for each of
our checks. Let’s see how this can be
done.
First, we will change
all of our self keywords to this.
The text to enter is as follows:
function MyChecks()
//Defines the structure.
{
this.number;
this.date;
this.payee;
this.amount;
this.display = display;
}
function display()
{
document.write("<b>Check
Number: </b>" + this.number + "<br>");
document.write("<b>Check Date:
</b>" + this.date + "<br>");
document.write("<b>Check
Payee: </b>" + this.payee + "<br>");
document.write("<b>Check
Amount: </b>$" + this.amount + "<br>");
}
Observe what has been added here:
this.display = display;
The above line represents a method.
This method is defined in the
function by the same name display. What you have above is a representation of a
class. When you do the following:
_101 = new MyChecks( );
You create an object based on the class
MyChecks.
This new object (_101) now has properties and methods, both of which are defined in the class MyChecks.
For example, one of the proprieties
of the object (_101) is the check
number:
_101.number = 101;
And it’s method is:
_101.display();
Now, to display the properties of
any check from the browser, all you need to enter is:
_102.display( );
You don’t need any other code,
outside of the code you use to get the text document that contains the required
class and it’s data:
<script src = “data1.txt”>
</script>
<script>
_103.display();
</script>
To see all of this in action, enter
the following code in your data1.txt file:
//My Data1 Class
function MyChecks() //Defines the structure.
{
this.number;
this.date;
this.payee;
this.amount;
this.display = display;
}
function display()
{
document.write("<b>Check
Number: </b>" + this.number + "<br>");
document.write("<b>Check Date:
</b>" + this.date + "<br>");
document.write("<b>Check
Payee: </b>" + this.payee + "<br>");
document.write("<b>Check
Amount: </b>$" + this.amount + "<br>");
}
//Data Follows:
_101 = new MyChecks();
_101.number = 101;
_101.date = "10/23/02";
_101.payee = "Tom Smith";
_101.amount = 12.43;
_102 = new MyChecks();
_102.number = 102;
_102.date = "10/25/02";
_102.payee = "Mary Jones";
_102.amount = 75.24;
_103 = new MyChecks()
_103.number = 103;
_103.date = "11/05/02";
_103.payee = "John Johnson";
_103.amount = 103.15
And in your html document, you only
need the following:
<script
src = "MyData/data1.txt"></script>
<script>
_103.display();
</script>
All you need do now is to change the
object identifier to see the data on a different check. For example, to see check 101:
_101.display();
Hiding the programming details
through the use of a class is called encapsulation. Encapsulation allows us to build truly self-contained program
components that may be designed, implemented, and tested separately and then
integrated into a larger program system.
Using a class allows us to
make instances of that class called objects which now exhibit properties and methods defined by that class. The methodology presented here is called object oriented programming (OOP). OOP is a powerful tool for developing
programs that have reusable components which can be used by other programs.
What Students Have Learned in the
Exercise
·
A review of objects -
properties and methods.
·
The similarity
between a structure and a class.
·
The idea that the
main difference between a structure
and a class is that a class has methods and a structure does not.
·
The concept that a class serves as a blueprint for an
object.
·
The idea of encapsulation where truly self-contained
components may be built.
·
How to simulate the
concepts of a class using JavaScript.
·
That instances of a class are referred to as objects.
·
The idea that object oriented programming is a
powerful software development tool.
·
Through OOP, a programmer can develop reusable
components which may now be used in other programs.
13. Arithmetic
Operators
In programming an operator is a symbol or set of symbols
that cause some process to take place. Arithmetic operators are those symbols
that cause a mathematical process to take place. The table below shows the arithmetic operators that are common to
most all programming languages:
Arithmetic Operators
|
Operator |
Description |
Example |
Result |
|
+ |
Addition |
3 + 4 |
7 |
|
- |
Subtraction |
5 - 2 |
3 |
|
* |
Multiplication |
3 * 2 |
6 |
|
/ |
Division |
6/2 |
3 |
|
% |
Modulus - Returns the remainder after
the first division. |
5 % 2 |
1 |
|
++ |
Increment |
X = 5 X++ |
6 |
|
-- |
Decrement |
X = 5 X-- |
4 |
Operator
precedence is the order that a program uses to perform processes using
operators. For example:
3 + 1 * 2 = 5
To get the above results, the multiplication had to be done
before the addition. If the addition
were done first, the answer would then be 8, not 5. What this means is that your program will do multiplication first
before it does division. As a matter of
fact, your program will do multiplication and division first then addition and
subtraction.
To test the result of an arithmetic
operations, you can simply use:
<script>
var answer;
answer = 3 + 1 * 2;
document.write(answer);
</script>
The above will cause 5 to be displayed on the browser.
You may use parenthesizes to tell
the program that you want things done in a different order. For example, suppose you really wanted to
add first, before you multiplied. You
can do this by using parenthesizes, because all operations inside them are
preformed first.
(3 + 1) * 2 = 8
In the above example, the 3 and 1
were added first (giving 4) and this result was then multiplied by 2 to give us
the answer of 8.
You may use as many parenthesizes as
you wish in an arithmetic expression, as long as you make sure that they are
properly nested. This means that for every opening
parenthesizes ( you have a closing
one ). As an example:
<script>
var answer;
answer = ((10 - 2)/ (3 + 1)) *
10 ;
document.write(answer);
</script>
Will cause 20 to appear on the browser.
The ++ and -- arithmetic operators may at first seem
strange. However in C, C++, C#, and
Java, as well as JavaScript, these operators play a useful role in incrementing
and decrementing. This process is most
often used in counting loops were the program will repeat a block of code for a
certain number of times.
What Students Have Learned in the
Exercise
·
The definition of a
program operator.
·
What are arithmetic operators.
·
The arithmetic
operators used in the most common programming languages.
·
Arithmetic operator precedence.
·
How to determine the
value of an arithmetic operation using JavaScript.
·
The use of
parenthesizes in arithmetic operations.
·
Nesting of
parenthesizes.
·
The use of the ++ and -- operators in programming.
14. Comparison
Operators
A comparison operator is a
symbol or group of symbols that compare one piece of data to another. The result of a comparison operation can be only true or false. Comparison operators used in JavaScript, C,
C++, C#, and Java are shown in the following table with examples of each.
Comparison Operators
|
Operator |
Description |
Example |
Result |
|
== |
Is equal to |
6 == 6 |
true |
|
!= |
Is not equal to |
6 != 6 |
false |
|
> |
Is greater than |
6 > 4 |
true |
|
< |
Is less than |
6 < 4 |
false |
|
>= |
Is greater than or equal to |
6 >= 6 |
true |
|
<= |
Is less than or equal to |
4 <= 6 |
true |
|
|
|
|
|
Comparison
operators are most useful in creating those parts of a program that make
decisions based on a true or a false condition. For example, a program could be written to
display the names of all students who are under the age of 21. The code would contain a statement similar
to the one shown below:
if (student.age < 21)
document.write(student.name)
In the above example, the variable student.age would contain the age of a
student taken from a data file and test if that value is less than 21. If the result is true then the student’s name would be displayed. If the result were false (meaning that the student was 21 or older), then no name
would be displayed.
You can test comparison operators in
JavaScript as follows:
<script>
var Result;
Result = 13 < 15;
document.write(Result);
</script>
When the above code is viewed
through the browser, the display on the browser will be:
true
You may consider having the students
try the examples presented on the Comparison Operators Table, given above.
What Students Have Learned in the
Exercise
·
The definition of a comparison operator.
·
A comparison
operation returns only a true or a false result.
·
The comparison
operators used in the most common programming languages.
·
Examples of the
comparison operators.
·
An example of where a
comparison operator.
·
How to use JavaScript
to show the results of a comparison operation.
14. Assignment
Shorthand Operators
An assignment shorthand operator is a convenient way of coding many
common arithmetic operations. Fore
example, one common arithmetic operation used in programming is to increase the
value of a variable by a certain amount:
x = x + y
In the above example, if x = 5 and y
= 3, then the new value of x would be 8.
Keep in mind that the = sign in JavaScript (as well a C, C++, C#, and
Java) means assignment, it does not mean equal (the == means equal).
The assignment shorthand for the
above example would be:
x += y (means exactly the same as: x = x + y).
The following table illustrates the
assignment operators along with an example of each one.
Assignment Shorthand Operators
|
Operator |
Example |
Is the same as |
|
+= |
x += y |
x = x + y |
|
-= |
x - = y |
x = x - y |
|
*= |
x *= y |
x = x * y |
|
/= |
x /= y |
x = x/y |
|
%= |
x %= y |
x = x%y |
As before, you can test each of the
above assignment shorthand operators in JavaScript as follows:
<script>
var x;
var y;
x = 6;
y = 2;
x += y;
document.write(x);
</script>
The above code will return 8 on the browser.
You should have the students try
several examples of the assignment shorthand operators using JavaScript.
What Students Have Learned in the
Exercise
·
The definition of an assignment shorthand operator.
·
The reason for the
use of such operators.
·
The assignment
shorthand operators used in the most common programming languages.
·
An example of using
an assignment shorthand operator.
·
How to use JavaScript
to show the results of a comparison operation.
16. Logical
Operators
A logical operator is a symbol or set of symbols used to perform a true and/or false comparison. The
results of such an operation will always produce either a true or a false
condition. In JavaScript, there are
three logical operators. These are
illustrated in the following table along with some examples of each.
Logical Operators
|
Operator |
Description |
Example |
Results |
|
&& |
and |
x = true y = true x && y |
true |
|
|| |
or |
x = true y = false x || y |
true |
|
! |
not |
x = true !x |
false |
It is helpful to understand the
operation of these operators. This is
best done using a truth table. Such a table shows the results of logical
operation for all possible conditions.
What follows are the truth tables for each of the logical operators:
AND Operation Truth Table
|
X Condition |
Y Condition |
Operation |
Result |
|
false |
false |
X && Y |
false |
|
false |
true |
X && Y |
false |
|
true |
false |
X && Y |
false |
|
true |
true |
X && Y |
true |
OR Operation Truth Table
|
X Condition |
Y Condition |
Operation |
Result |
|
false |
false |
X || Y |
false |
|
false |
true |
X || Y |
true |
|
true |
false |
X || Y |
true |
|
true |
true |
X || Y |
true |
Note from the above that an AND operation produces a true output only when both conditions
are true. Compare this to the OR
operation where a false output is
produced only when both conditions are false.
The not operation truth table is almost trivial. However, as you will discover, this is a
very important operation in the construction of programs that use Artificial
Intelligence and Expert Systems.
NOT Operation Truth Table
|
X Condition |
Operation |
Result |
|
false |
!X |
true |
|
true |
!X |
false |
You can test the results of the
above truth tables in JavaScript as follows:
<script>
var x;
var y;
var Result;
x = true;
y = true;
Result = x && y;
document.write(Result);
</script>
The above code will return the value
of true on the browser.
There are many uses of these
operators with comparison operators. As
an example, suppose you wanted to find the names of all employees in a company
who where between the ages of 21 and 64.
The code to do this would be:
if (employee.age >= 21)
&& (employee.age <= 64)
document.write(employee.name);
What the above statement says,
is: “If the employee’s age is greater
than or equal to 21 and if the
employees age is less than or equal to 64, then display the employee’s
name.” If these conditions are not met,
then don’t display anything.
Here is an example using the or condition. Suppose you wanted to see a listing of all students who were less
than 18 years of age or older then 35.
This may be an age requirement for a dorm, where only students between
the ages of 18 and 35 could be a resident.
The code to do this would be:
if
(student.age < 18) || (student.age > 35)
document.write(student.name);
What the above statement says,
is: “If the student’s age is less than
18 or the students age is greater
than 35, then display the student’s name.”
If these conditions are not met, then don’t display anything.
Now let’s use the not operator. Suppose we had the same problem as above with student age limits
for a dorm. But this time we wanted to
display the names of students that were within that age group. In other words, not the previous conditions.
The code to do this would be:
if !((student.age < 18) ||
(student.age > 35))
document.write(student.name);
What the above statement says,
is: “If the following condition is not true, then display the student
name. The condition is: if the student
age is less than 18 or the student age is greater than 35.” The results of this will produce the names
of all students who’s ages fall between 18 and 35 inclusive.
As you will discover, there is great
programming power when you combine the logical operators with the comparison
operators.
What the Student has Learned in
this Exercise
·
The definition of a logical operator.
·
Examples of the
logical operations.
·
What are truth tables.
·
The AND operation.
·
The OR operation.
·
The NOT operation.
·
How to test a logical
operation using JavaScript
·
Programming examples
of combining logical operators with comparison operators.
17. Arrays
The word array comes from the word arrangement. An array is a collection of the same
variable identifier where each member of the collection is distinguished by a
number called the index. An example of an array elements are:
MyArray[0];
MyArray[1];
MyArray[2];
MyArray[3];
Note the use of the left and right
brackets [ ] which contain the value
of the array index. Each of the above
array elements may hold a different value.
To start a new array in JavaScript,
we do the following:
<script>
MyArray = new Array(3);
</script>
The JavaScript Array object has an argument, where the value placed in that
argument will be the number of array elements that the array variable MyArray will have. It should be noted that all array elements
start with an index of 0. As an
example:
<script>
MyArray = new Array(3);
MyArray[0] = “First element.”; //Starting with an index of 0.
MyArray[1] = “Second element.”;
MyArray[2] = “Third element.”; //Total of 3 array elements.
document.write(MyArray[0] +
“<br>”);
document.write(MyArray[1] +
“<br>”);
document.write(MyArray[2] +
“<br>”);
</script>
When the above is executed through a
browser, the output will be:
First
element.
Second
element.
Third
element.
Arrays have many applications in programming. As an example, we can now make a more
powerful student database through the use of arrays.
Consider
the following program code:
function Person() //Sets up the class Person
{
this.name;
this.age;
}
Student = new Array(1000); //Makes an array of Student for 1000
entries.
var IDIndex; //Variable for the array index.
// Student data
follows:
Student[100] = new Person();
Student[100].name = "George
Henry";
Student[100].age = 18;
Student[101] = new Person();
Student[101].name = "Mary
Either";
Student[101].age = 17;
Student[102] = new Person();
Student[102].name = "Harry Pottsfield";
Student[102].age = 32;
Student[103] = new Person();
Student[103].name = "Helen
Kronker";
Student[103].age = 23;
//Gets the value of the array index from
the user.
IDIndex = prompt("Enter the student ID:
", "Between 100 and 103, inclusive");
//Displays the information for the selected
student.
document.write("<b> Name:
</b>" + Student[IDIndex].name + "<br>");
document.write("<b> Age:
</b>" + Student[IDIndex].age);
</script>
Analyzing the above program we have the class definition:
function
Person() //Sets up the class Person
{
this.name;
this.age;
}
As
can be seen from above, there are only two properties in the class Person.
They are: name and age.
Next,
there is the declaration of the array:
Student = new
Array(1000);
The above declaration creates the Student array with enough space for
1,000 array elements.
Next, a new variable is declared:
var
IDIndex;
The above variable IDIndex
will be used as the number for the array index. What follows next are the student data, an example of which is
shown below:
Student[100]
= new Person();
Student[100].name = "George Henry";
Student[100].age = 18;
The first line creates a new array element, with an array
index of 100. Note that we could have
chose any number between and including 0 to 999 (recall that the value of the
first array element is always 0).
On the next two lines, the name and age proprieties are assigned values. In this case the value for the name property is “George Henry”,
and the value assigned to the age property is 18. There are then three other student array elements, each with a
unique array index (they are 101, 102, and
103.)
The next important programming
statement:
IDIndex = prompt("Enter the student ID: ",
"Between 100 and 103, inclusive");
The above sets the IDIndex to the value entered by the
program user in the prompt box that
will appear over the browser. The user
is asked to enter a student ID with values between 100 and 103, inclusive. These values, 100, 101, 102, and 103 are the
value of each unique array index, and each one represents a unique student.
The last two program statements:
document.write("<b> Name: </b>" +
Student[IDIndex].name + "<br>");
document.write("<b> Age: </b>" +
Student[IDIndex].age);
The above two statement display the assigned attributes of
the student object for the selected array index. For example, if the program user entered the value of 101 for the
student ID, then the Student[IDIndex].name
and the Student[IDIndex].age would
have the values of Student[101].name and
Student[101].age, and then display
the attributes assigned to the Student[101] array element:
Name:
Mary Either
Age: 17
Arrays give us a powerful means of
working with all kinds of data. In
future sections, you will see more of arrays at work.
What the Student has Learned in
this Exercise
·
The definition of an array.
·
The use of an array index.
·
The syntax for
representing array elements.
·
The concept that each
array element may contain a different value.
·
How to define a new
array in JavaScript.
·
Information about the
JavaScript Array object.
·
The fact that an
array index starts with 0.
·
An example of using
arrays with a class.
·
The concept of making
the array index a variable.
18. Program
Interaction with Databases
A database can be thought of as a way of organizing data. You can think of data as the raw facts and figures.
One of the most common ways of organizing data is in a table. A sample Student
Database is shown below:
Student Database
|
ID |
Name |
Age |
Status |
GPA |
|
100 |
George Henry |
18 |
Freshman |
2.68 |
|
101 |
Mary Either |
17 |
Freshman |
3.98 |
|
102 |
Harry Pottsfield |
32 |
Sophomore |
1.98 |
|
103 |
Helen Kronker |
23 |
Junior |
2.98 |
|
104 |
Alice Jones |
21 |
Senior |
3.5 |
It is important that we understand
the terminology which is used to describe the various parts of the above
table. Once this is done, we can then
use that same terminology to discover how a program can interact with the above
database. Let’s look at some of these
important terms while referring to the above Student Database table.
Note that the above table has five columns. Each of these columns is assigned a name. The name of the first column is ID, that of the second Name, the third Age, the forth Status,
and the last is GPA. In database terminology, these columns are
called fields. A field is a group of related data. For
example, look at the first field called ID.
All of the data in that field are whole numbers, and none of them are
duplicated (You wouldn’t want to have two or more students with the same ID
number, that could be real confusing.)
The data in the name field is
a person’s name. Here, there could be
two students with the same name, however, they would still have different
student Ids. The next field Age also contains a group of related
data which are whole numbers which may be the same - Realizing that more than
one student could be the same age. The
next field, status
contains a group of related data which tells us what “year” the student is in
at the time the data were created. The
last field, GPA contains numbers
which may be decimal fractions.
Since we now know that each column
in a table is called a field and
contains a group of related data,
let’s now turn our attention to each of the rows
in the above table.
In a database, each row represents one record. A record is a group of related fields.
For example, look at the first record.
It has an ID, name, age, status, and GPA for one student. In effect, this single row represents that
students record. Note in the above table that there are five records, representing a total of five
students.
There is one very important point to
recognize in a database. That is the
idea of a primary key. A primary key is a field or group of fields
which uniquely and minimally identifies a unique record and
cannot have any duplicates. Look again at the above table. The only field which uniquely and minimally
identifies each record is the ID field.
Recall we said that this field could not have any duplicates. That being the case, the ID field is the primary key for this table of data. In what follows, we will use this primary
key to uniquely identify each of our records.
What we now want to do is to put the
above table of data into a form that can be understood by our program. Generally the first step is to convert the
structure of the table into a program structure. Recall that the difference between a class and a structure is that a structure had only attributes and no methods.
Using JavaScript, the following code
has converted the above table structure into a program structure.
<script>
function Students()
{
this.ID;
this.Name;
this.Age;
this.Status;
this.GPA;
}
</script>
If you run the above through your
browser, nothing will happen. Be sure
to compare this structure to the original table. What you will see is that each of the structure elements correspond to each of the
table’s fields (we even give them the
same name).
Are next step is to create a set of records. We will do this by using the JavaScript Array object as follows:
MyStudents = new Array(1000);
MyStudents
can now contain a maximum of 1,000 records!
Next, we will assign data to
each of the records:
MyStudents[100] = new Students( )
MyStudents[100].ID = 100;
MyStudents[100]. Name = “George Henry”;
MyStudents[100].Age = 18;
MyStudents[100].Status = “Freshman”;
MyStudents[100].GPA = 2.68;
Compare the above entry to the
Student Database table. Note that this
entry represents one record. Also note that the array index is the same as the student ID. What this means, and
this is very important, is that we can use the array index as the primary key for each of our
records! This is an meaningful concept
when it comes to having programs interact with databases. We will use this concept later when we
present data mining.
We
can now put all of this data, along with the data structure definition,
in a separate text file. Once that is
done, we can then use our program to interact with the data in the text
file. Shown below is the text to be
entered into the separate text file. We
named this file: StudentData.txt
var IDIndex;
function
Students()
{
this.ID;
this.Name;
this.Age;
this.Status;
this.GPA;
}
MyStudents
= new Array(1000);
MyStudents[100] = new Student();
MyStudents[100].name = "George
Henry";
MyStudents[100].age = 18;
MyStudents[100].status =
"Freshman";
MyStudents[100].gpa = 2.68
MyStudents[101] = new Student();
MyStudents[101].name = "Mary
Either";
MyStudents[101].age = 17;
MyStudents[101].status =
"Freshman";
MyStudents[101].gpa = 3.98;
MyStudents[102] = new Student();
MyStudents[102].name = "Harry
Pottsfield";
MyStudents[102].age = 32;
MyStudents[102].status =
"Sophomore"
MyStudents[102].gpa = 1.98;
MyStudents[103] = new Student();
MyStudents[103].name = "Helen
Kronker";
MyStudents[103].age = 23;
MyStudents[103].status =
"Junior";
MyStudents[103].gpa = 2.98;
MyStudents[104] = new Student();
MyStudents[104].name = "Alice
Jones";
MyStudents[104].age = 21;
MyStudents[104].status =
"Senior";
MyStudents[104].gpa = 3.5;
Next, in the script
that goes with our browser, we would enter:
<script src = “StudentData.txt”>
</script>
<script>
IDIndex = prompt("Enter the student ID:
", "Between 100 and 104, inclusive");
document.write("<b> Name:
</b>" + Student[IDIndex].name + "<br>");
document.write("<b> Age:
</b>" + Student[IDIndex].age + "<br>");
document.write("<b> Status:
</b>" + Student[IDIndex].status + "<br>");
document.write("<b> GPA:
</b>" + Student[IDIndex].gpa);
</script>
The above program now gives us the
ability to look at the contents of any record in our student database. All we need do is to enter the student ID
number to see all of the other data related to that one student.
By the way, it doesn’t take much
more to convert our structure into a
class. All we need to do is add a
method. We can go back to our text file
and make the following modification to our structure and add the ShowIt method to it:
var IDIndex;
function Person()
{
this.name;
this.age;
this.status;
this.gpa;
this.ShowIt = ShowIt;
}
function ShowIt()
{
document.write("<b> Name:
</b>" + Student[IDIndex].name + "<br>");
document.write("<b> Age:
</b>" + Student[IDIndex].age + "<br>");
document.write("<b> Status:
</b>" + Student[IDIndex].status + "<br>");
document.write("<b> GPA:
</b>" + Student[IDIndex].gpa);
}
Once this is done, we can go back to
our JavaScript browser program and just have the following code:
<script>
IDIndex =
prompt("Enter the student ID: ", "Between 100 and 104,
inclusive");
Student[IDIndex].ShowIt();
</script>
Note how much simpler the above
coding is when we use object oriented
programming. You will be using the
concepts presented here again in this series of lessons. The interaction of a program with a database
is a very powerful tool for this information age.
What the Student has Learned from
this Exercise
·
The definition of a
database.
·
The definitions of
the terms used to describe the various parts of a table of data.
·
The relationships
between the various parts of a table of data.
·
The relationship
between a record and table data.
·
The concept and
definition of a primary key.
·
How to convert a
table structure into a program structure.
·
The relationship
between a table structure of data and a program structure of data.
·
Using the Array
object to create a group of records.
·
The concept of using
the array index as the primary key for a program record.
·
A review of
separating data from programming instructions.
·
Using the array index
as a primary key to locate and display a specific record.
·
Converting the structure into a class to simplify program coding.
19. Putting the for Loop to Work
Recall that a program loop simply causes a specific block of
code to be repeated one or more times.
One of the most common programming loops is the for loop. The syntax is shown
below:
for
(count = 0; count < 6; ++count)
{
//Block of code to be
repeated
}
The above is the same syntax used in
C, C++, C#, and Java as well as JavaScript.
Here is what the for loop syntax means.
The count = 0; tells the for reserved word where to start its counter (represented here by the
identifier count). Note that this ends with a semicolon. The next item, count < 6; tells the for
under what condition the count will end (and the looping will stop). Note again, this is terminated by a
semicolon. The last term ++count tells the for how much to increment (or decrement) the count by each time the
loop is completed. There is no
terminating semicolon used here. The
semicolons are used here to separate the three counting conditions. As an example, consider the following code:
<script>
for (x = 0; x <= 5;
++x)
{
document.write(“Value of x is :” + x);
document.write(“<br>”);
}
</script>
When the above is run through the
browser, the output will be:
Value
of x is: 0
Value of x
is: 1
Value of x
is: 2
Value of x
is: 3
Value of x
is: 4
Value of x
is: 5
Observe from the above that this
time the counting variable used was x. You may use any legal variable identifier to
serve as the counting variable.
We will now demonstrate the use of a
for loop and control structures to find specific information from a given
database. The ability to do this is one
of the cornerstones of the information age.
First, listed below is the separate text file data:
var
IDIndex;
function Person()
{
this.ID;
this.name;
this.age;
this.status;
this.gpa;
this.ShowIt = ShowIt;
}
function ShowIt()
{
document.write("<b> ID:
</b>" + Student[IDIndex].ID + "<br>");
document.write("<b> Name:
</b>" + Student[IDIndex].name + "<br>");
document.write("<b> Age:
</b>" + Student[IDIndex].age + "<br>");
document.write("<b> Status:
</b>" + Student[IDIndex].status + "<br>");
document.write("<b> GPA:
</b>" + Student[IDIndex].gpa);
document.write("<hr>");
//Gives a horizontal line.
}
Student = new Array(1000);
Student[100] = new Person();
Student[100].ID = 100;
Student[100].name = "George
Henry";
Student[100].age = 18;
Student[100].status =
"Freshman";
Student[100].gpa = 2.68
Student[101] = new Person();
Student[101].ID = 101;
Student[101].name = "Mary
Either";
Student[101].age = 17;
Student[101].status =
"Freshman";
Student[101].gpa = 3.98;
Student[102] = new Person();
Student[102].ID = 102;
Student[102].name = "Harry
Pottsfield";
Student[102].age = 32;
Student[102].status =
"Sophomore";
Student[102].gpa = 1.98;
Student[103] = new Person();
Student[103].ID = 103;
Student[103].name = "Helen
Kronker";
Student[103].age = 23;
Student[103].status = "Junior";
Student[103].gpa = 2.98;
Student[104] = new Person();
Student[104].ID = 104;
Student[104].name = "Alice
Jones";
Student[104].age = 21;
Student[104].status = "Senior";
Student[104].gpa = 3.5;
Student[105] = new Person();
Student[105].ID = 105;
Student[105].name = "Jimmy
Jones";
Student[105].age = 18;
Student[105].status = "Junior";
Student[105].gpa = 3.3;
Student[106] = new Person();
Student[106].ID = 106;
Student[106].name = "John Baker";
Student[106].age = 19;
Student[106].status = "Senior";
Student[106].gpa = 1.75;
Student[107] = new Person();
Student[107].ID = 107;
Student[107].name = "Harry Sims";
Student[107].age = 17;
Student[107].status = "Freshman";
Student[107].gpa = 3.5;
You may copy and paste the above
data file (which also contains a class
identified as person. Save the above in a text file called
StudentData.txt .
What follows now is the program code
to be operated through the browser:
<script
src="StudentData.txt">
</script>
<script>
for (IDIndex = 100; IDIndex <= 200;
++IDIndex)
{
if ((Student[IDIndex].age <= 18)
Student[IDIndex].ShowIt();
}
</script>
Observe the for statement. The counter
variable IDIndex starts at 100 and
goes to 200, incremented by 1 (the student ID Index starts at 100 in the
database).
Next, the conditional statement:
if ((Student[IDIndex].age <=
18)
Student[IDIndex].ShowIt();
Here, the if says: “If the Student’s
age is less than or equal to 18 then show the student record.” When the above script code is run through
the browser, all of the student records which meet the above criteria will be
displayed.
At this point, you should have the
students try various combinations of conditions. This should include the use of the || (or) as well as the &&
(and) with the database.
What the Student has Learned in
this Exercise
·
The syntax of the for loop.
·
The meaning of each
part of the for syntax.
·
An example of using
the for loop.
·
The use of the
counter variable in the for loop.
·
An application of the
for loop with a database using
control structures to find data matching specific criteria.
20. Control
Structures - The if, if-else, and switch Statements and the Conditional Operator
The if statement was introduced in the last section. Recall that you used the if statement under the conditions that
you wanted to execute some code if a certain condition were true. The syntax is:
<script>
If (condition)
{
//Code to be executed.
}
//Program continues…
</script>
In the above code, if the condition is true, then the //Code to be
executed section will be executed
and then //Program continues… will be
executed. If, however, condition is false, then //Code to be
executed will be skipped and the only thing executed will be //Program continues…
As an example, if we were analyzing
a student database and wanted to automatically be alerted to any student who
was under the age of 21, we could do the following:
<script>
if (student.age < 21)
{
document.write(“This student is under 21.”);
document.write(“<br>”);
}
document.write(student.name);
</script>
In the above code, if student.age is less than 21, then the
following will appear on the browser (assume the student.name is Harry Noodle):
This student is under 21.
Harry
Noodle
However, if student.age
is 21 or greater, then the
following will appear on the browser:
Harry Noodle
The if statement
is used when we want to execute a set of code if a certain condition is true.
Now, suppose we wanted to execute a set of code if a condition were true
or a different set of code if a condition were false. Suppose, for example, we wanted a program that will tell us if a
student has a passing or a failing grade.
The condition would be that if the students grade is over 65, they are
passing, and if the grade is 65 or less, they are failing. The code could be presented as follows:
<script>
if (student.grade <= 65)
{
document.write(“Sorry, this student
is failing! <br>”);
document.write(“Student may not
continue registration.”);
}
else
{
document.write(“OK, this student has
passed!”);
document.writre(“Have student
continue registration.”);
}
document.write(student.name);
</script>
For the above example, if the
student’s grade were less than or equal to 65, then the following would appear
on the browser:
Sorry, this student is failing!
Student
may not continue registration.
Harry
Noodle
Now, if the student’s grade were greater then 65, the
following would appear on the browser:
OK, this student has passed!
Have
student continue registration.
Harry
Noodle
If you have several different blocks of code to be executed,
depending on several different conditions, then you use the switch statement. The syntax is shown below:
switch(condition)
{
case value1: //Code to be executed for value1.
break:
case value2: //Code to be executed for
value2.
break;
case value3: //Code to be executed for
value3.
break;
default: //Code to be executed if none of the condition does note equal
any of the
//previous values.
}
In the above code segment, condition is a variable. If it is equal to value1 then the code that follows will be executed. The keyword break tells the program when to stop executing the code for the value1 condition. If the break
were not there, then code execution would continue down into case value2:. The same applies to the other cases. The default
will execute its code if none of the given conditions were met.
As an example of a switch application, consider the
following:
<script>
var grade;
var points;
grade = prompt("Enter a letter grade:
", "");
switch (grade)
{
case "A": points = 4.0;
break;
case "B+": points = 3.5;
break;
case "B": points = 3.0;
break;
case "C+": points = 2.5;
break;
case "C": points = 2.0;
break;
case "D+": points = 1.5;
break;
case "D": points = 1;
break;
case "F": points = 0;
break;
default:
document.write("No proper letter
grade." + "<br>");
}
document.write("Points: " +
points);
</script>
The above set of code will convert a
letter grade into points. Note that no
A+, or F+ is allowed. Also note that no
- minus grades are allowed. If the user
does not obey these rules then the default
message is displayed.
The conditional operator assigns a value to a variable depending on a
specific condition. The syntax is:
variablename=(condition)?value1:value2
If the condition is true, then variablename
will be assigned value1. If the condition
is false, then variablename will be assigned value2. Here is an example of the conditional operator.
<script>
var points;
var statement;
points = prompt("Enter the number of
points: ", "");
statement = (points > 65)?"You
pass!":"You fail!";
document.write(statement);
</script>
In the
above program, if the value of points
is greater than 65, then the output will be:
You pass!
If, in
the same program, the value of points
is 65 or less, then the output will be:
You fail!
In
any programming language, conditional statements, play an important role. The syntax for the conditional statements
you learned here are the same for C, C++, C#, and Java. You will discover that the backbone of
programs which help us analyze data will freely use these different conditional
statements.
What the Student has Learned in this Section
·
A review of the if statement.
·
The difference
between the if and if-else statements.
·
Examples of the use
of the if and if-else statements.
·
The syntax for the switch statement.
·
An example of the use
of the switch statement.
·
The syntax for the conditional operator.
·
An example of the use
of the conditional operator.
21. Loops - do while and while do
Recall
that you need only three structures to solve any programming problem. They are sequence,
branching, and iteration. You have just had several examples of branching with the if, if-else, and conditional
operator. You also had an
introduction to iteration with the
use of the for loop. The primary use of the for loop is when you know how many times the program will repeat
the same set of code. However, there
are times when you do not know this.
For example, you may ask the program user if they wish to repeat the
program. You don’t know ahead of time
what their answer will be or even how many times they may choose to repeat it.
The
syntax for the do while loop is:
|
|
do
{
//The code to be repeated goes here.
//This is the body of the do while
loop.
}
while (condition);
//Rest of the program goes here.
As seen
in the above code, you start with the keyword do. This is following by a
pair of braces which is where the code you want repeated will go. The keyword while ends the loop and tests a condition As long as condition is true the
loop will be repeated. When the condition is false, the loop will end and the rest of the program will continue.
Here is
an example of asking the user if they wish to repeat a program.
<script>
var DoAgain;
do
{
document.write("This is my program.
<br>");
DoAgain = confirm("Do you want to
repeat this program?");
}
while (DoAgain == true);
document.write(“Thanks
for using my program.”);
</script>
In the
above code, the user will see This is my
program on the browser and a confirm box. A confirm box has a
message (Do you want to repeat this
program?) and two buttons. One
button says OK and the other Cancel. If the user clicks on the OK
button, then the results returned are true. If, however, the user clicks on the Cancel button, then the results
returned will be false. As long as the user clicks on the OK button, the program will be
repeated. If the Cancel is selected, the program will stop and the user will see:
Thanks for using my program.
…on the
browser.
The
important point to recognize about the do
while loop is that the body of the loop will be done at least once, because
the condition is not checked until
after execution of the loop’s body code.
If you
want a condition tested before the body of the loop code is executed, you would
use the while do loop. The syntax for this loop is shown below:
while(condition)
{
//Code to be executed.
//Body of the loop.
}
//Rest of program continues.
In the
above code, if the condition is true then the body of the loop (the code
between the brace set) will be executed.
If, however, the condition is false, the body of the code will not be
executed and the program will continue with the rest of the program.
Here is
an example of using the while do:
<script>
var
IDo;
IDo
= confirm("What to see my neat program?");
while(IDo)
{
document.write("My really neat
program. <br>");
IDo = confirm("What to see it
again?");
}
document.write("Thanks
again.");
</script>
In the above code a confirm box appears first with the
message What to see my neat program? If the user selects the OK button, then the variable IDo
will be set to true and the Do loop will
execute the body statements which will display:
My really neat program.
And
cause the confirm box to appear again
with the message Want to see it
again? Again, if the user selects
the OK button, the loop will
repeat. However, if the user selects
the Cancel button the loop will not
be executed and the program will continue with the rest of the code. In this case the user will now see:
Thanks again.
Displayed
on the browser.
You
have now seen the three major kinds of loops.
The for loop which is used
when you know ahead of time how many times the loop will be repeated. The do
while loop which always executes the body of the loop at least once, and
the while do loop which will only
execute the body if the tested condition is true.
What the Student has Learned in this Exercise
·
A review of the three
programming structure of sequence,
branching, and iteration.
·
The use of the for loop.
·
The syntax of the do while loop.
·
Purpose of the do while loop.
·
An example of the do while loop.
·
Introduction to the confirm dialog box.
·
The syntax of the while do loop.
·
Purpose of the while do loop.
·
An example of the while do loop.
22. Functions with
Parameters
You
have already used parameters in
previous sections. Recall that the
document method write required a parameter. This is what the document.write( ) method was to write (display
on the browser). As an example:
document.write(“This is the parameter!”);
When the above is executed, the browser will display:
This is the parameter!
The ability to pass values through a parameter becomes a very powerful programming feature. You can create your own functions that can
have parameters passed on to them. The
basic syntax for doing that is:
function FunctionIdentifier(argument1,
argument2, … argumentN)
{
//Body of the function.
}
From the above example observe that the function is declared the way we have done functions up to this
point. However, now, within the
parenthesizes (which all functions must have) is an argument list. This list (argument1, argument2, … argumentNI) are
the variable identifiers that you
wish to pass to the function. The following example illustrates - When it
is executed, the number 5 will
appear on the browser:
<script>
function ShowIt(Num1)
{
document.write(Num1);
}
var Num1;
Num1 = 5;
ShowIt(Num1);
</script>
First look at the function
definition:
function ShowIt(Num1)
{
document.write(Num1);
}
The
argument is Num1, it is simply a variable identifier (which must obey all the
rules of any variable identifier), which is placed within the parenthesizes
immediately following the function identifier. The same variable identifier my now be used within the body of
the function where you may do whatever you wish with it. In the above example, we are simply having
it’s value displayed on the browser.
Here is how it gets it’s value:
var Num1;
Num1 = 5;
ShowIt(Num1);
Here the variable identifier is
declared, assigned the value of 5, and then passed as a parameter to the called function.
In this example, we use the variable identifier Num1 to pass the value of 5
to the called function.
All of this seems like a lot of work
just to get the browser to display the number 5, and it is. However, what
is important here is that you understand the terminology and, most importantly,
the concepts of creating your own functions with parameters. There are a few
more concepts that are important when designing functions with parameters. Consider the following program:
<script>
function ShowIt(Num1)
{
document.write(Num1 +
"<br>");
}
var Num1;
Num1 = 5;
MyNum = 6;
ShowIt(Num1); //Using the same identifier.
ShowIt(MyNum); //Using a
different identifier.
ShowIt(7); //Using the actual value.
ShowIt(3 + 5); //Using an operation.
</script>
The above example demonstrates four
ways of passing a value to a called function.
The first:
ShowIt(Num1);
Uses the same identifier
(Num1) as was used by the
function argument. The second:
ShowIt(MyNum);
Uses a different identifier (MyNum) from that used by the function argument.
The third:
ShowIt(7);
Uses
the actual value to be passed to the
function.
And the fourth:
ShowIt(3 + 5);
Does
an arithmetic operation, the results of which are passed to the same called
function. The point is, it makes no
difference which of the four methods you use as an argument. Any of these
methods will work. By the way, the
output on the browser of the above program will be:
5
6
7
8
You may also have more than one
argument in the argument list of a
function. Consider the following
program:
<script>
function AddThem(Num1, Num2)
{
var Answer;
Answer = Num1 + Num2;
document.write("The sum is: " + Answer);
}
AddThem(2, 3);
</script>
As you can see in the above program,
there are now two parameters in the function header. These are
represented by the variable identifiers Num1
and Num2, separated by a comma. These same identifiers are used in the
function body to have some kind of
operation preformed on them. In this
case they are simply being added and the result is displayed on the browser
using the document.write( ) method.
When the function is called:
AddThem(2, 3);
The
values to be added are placed as function parameters,
again separated by a comma. What is
important to see here is that the same number of parameters which must be passed to a function must be exactly the
same as the number of function arguments
used in the function definition. As an example, consider the following
program. It will produce an error:
<script>
function AddThem(Num1, Num2, Num3)
{
var Answer;
Answer = Num1 + Num2 + Num3;
document.write("The sum is: " + Answer);
}
AddThem(2, 3);
</script>
The
output of the above program on the browser will be:
The sum is: NaN
The NaN means Not
a Number and indicates an error.
Note the reason for this error. In the function header there are three arguments: Num1, Num2, and Num3.
However when the function is called
there are only two parameters: 2 and 3. This violates the rule
that there must be the same number of parameters
when calling the function as there are arguments
in the function definition. The program can be corrected as follows:
<script>
function AddThem(Num1, Num2, Num3)
{
var Answer;
Answer = Num1 + Num2 + Num3;
document.write("The sum is: " + Answer);
}
AddThem(2, 3, 4); //We now have three parameters
passed to the function.
</script>
When
the above program is executed, the browser will now display:
The
sum is: 9
So
far we have seen that functions can have arguments which are represented by
variable identifiers. These variables,
in turn, may then be processed within the body of the function. One other powerful feature of creating your
own functions, is that a function my return
a value. This is accomplished by using
the keyword return within the body of
the function. As an example:
<script>
function AddThem(Num1, Num2, Num3)
{
var Answer;
Answer = Num1 + Num2 + Num3;
return Answer;
}
var Result;
Result = AddThem(2, 3, 4);
document.write(Result);
</script>
Observe that now, within the
function definition, there is the keyword return. Immediately following this is the variable
identifier Answer. This identifier Answer contains the result of the addition of the three
numbers. This result is being returned to the called function.
Note also that when the function is
now called it is assigned to another
variable identifier - Result.
Result = AddThem(2, 3, 4);
The variable Result will now contain the value returned by the called function.
The rest of the code:
document.write(Result);
Simply
causes the value of Result to be
displayed on the browser. In this case
the number 9 will be displayed.
What we have seen here is that you
can pass values to a function, the function, in turn, can perform processes on
these values and then return the result of these processes. This is a very powerful feature of functions. The purpose of this section was to introduce
these concepts through some very simple applications. In future sections, we will put these concepts to use in larger
applications.
What the Student has Learned in
this Section
·
A review of passing
values through a function parameter.
·
The syntax used for
making a function argument list.
·
Functions may have
any number of arguments each
separated by a comma.
·
An example of passing
a value to a function from a function call.
·
The terminology of
the function definition, function header,
and function body.
·
Function arguments are variable identifiers which must obey the rules for
creating any identifier.
·
Example of four ways
of passing values to a function from a function call: Using the same identifier; using a different identifier, using
the value itself, and using an operation.
·
Example of having
more than one argument in the
function argument list.
·
There must be the
same number of parameters in a
function call as there are in the argument
list of the called function.
·
Functions my return a
value.
·
Use of the keyword return.
·
An example of a
called function returning a value.
·
The concept that a
function can accept values, process them, and return a result.
23. Local and
Global Variables
Recall that good programming
practice requires that before we use a variable, we must first declare that variable. To do this, we use the keyword var followed by the identifier that will be used to store the variable value.
There are actually two places within
the program where a variable my be declared.
One is outside of any function definition, the other is within the body
of the function definition. Those
variables declared outside of any function definition are called global variables. They are called global because such variables may now be used by any function
within the program. On the other hand,
variables declared within the body of the function definition are called local variables. They are called local because any such variable can now only be used by the
function which declared it.
Consider the following. It declares a global variable x and
assigns to it the value of 5. Since
this is a global variable, all
functions within the program will be able to recognize it.
<script>
var x;
x = 5;
function Function1( )
{
document.write("From Function1, x = " + x + "<br>");
}
function Function2( )
{
document.write("From Function2, x = " + x + "<br>");
}
Function1( );
Function2( );
</script>
When the above program is executed
through the browser the output will be:
From
Function1, x = 5
From
Function2, x = 5
As you can see, from the above output, both functions, Function1( ) and Function2( ) were able to use the value of the global variable x.
However, now consider the following
program. Here the variable identifier x is now declared locally within a function, Function1(
). Doing this now makes it a local variable which will not be able to
be used by any other function (like Function2(
)).
<script>
function Function1( )
{
var x;
x = 5;
document.write("From Function1, x = " + x + "<br>");
}
function Function2( )
{
document.write("From Function2, x = " + x + "<br>");
}
Function1( );
Function2( );
</script>
When the above program is executed, Function1( ) will display the value of 5, but, Function2( ) will cause an error because it does not know anything
about the variable which was locally
declared in another function.
You should note that variables
declared in the argument list of a function are treated as local variables as well.
It is considered good programming
practice to keep all variables local. There is good reason for this. Recall from previous sections that one
method of developing a program was to break the problem down into separate
parts. This was done through the use of
functions, where we had a function called main
and all this function did was call
the other functions. In large
programming assignments, this is the procedure used. The program is broken down into smaller, more manageable
parts. Then several programmers will be
assigned to work on the program, each being assigned one or more of these
separate parts.
Consider the following program
situation, where we have two programmers, George and Harry both working
independently on separate sections of the same program. They decide (incorrectly) to keep things
simple and use global variables. Here is the first code they come up with:
<script>
var x;
function George1()
{
x = 5;
document.write("From George1, x =
" + x + "<br>");
}
function Harry1()
{
x = 15;
document.write("From Harry1, x =
" + x + "<br>");
}
George1();
Harry1();
</script>
Note that both programmers use the
global variable x. George assigns a value of 5 to it in his
function George1( ) and Harry assigns
a value of 15 to the same variable in his function Harry1( ). When the program
is executed, the browser displays:
From
George1 x = 5
From
Harry1 x = 15
From the above output, we can see
that both programmers are happy, they each got the value they expected from
each of their functions. But now consider
the following. Harry writes another
function to display his value of x. The
program is shown below:
<script>
var x;
function George1( )
{
x = 5;
document.write("From George1, x =
" + x + "<br>");
}
function George2( )
{
document.write("From George1, x =
" + x + "<br>");
}
function Harry1( )
{
x = 15;
document.write("From Harry1, x =
" + x + "<br>");
}
George1( );
Harry1( );
George2( );
</script>
Look
at George’s new function George2( ). George figures that since he already
assigned his value of 5 to x in his first function, he doesn’t have to do that
again for his second function. However,
when the above program is now executed the output becomes:
From
George1 x = 5
From
Harry1 x = 15
From
George2 = 15
George’s second function George2(
) has now picked up the value of x from Harry’s function. This, of course, is not what George wanted
or expected.
The above illustration, though a
simple one, illustrates why the use of global
variables is discouraged in program development by professional programmers.
If the program being developed by
George and Harry had used local
variables instead, here is what their program would have looked like.
<script>
function George1( )
{
var x;
x = 5;
document.write("From George1, x =
" + x + "<br>");
}
function George2( )
{
var x;
x = 5;
document.write("From George1, x =
" + x + "<br>");
}
function Harry1( )
{
var x;
x = 15;
document.write("From Harry1, x =
" + x + "<br>");
}
George1( );
Harry1( );
George2( );
</script>
Now, when the above program is
executed the output on the browser would be:
From
George1 x = 5
From Harry1
x = 15
From
George2 x = 5
And now, there are no surprises, and both programmers
including their boss, are happy. So,
when developing programs avoid global
variables.
What the Student has Learned in
this Exercise
·
A review of declaring variables.
·
The two types of
variables, local and global.
·
The definition of a local and a global variable.
·
An example of using a
global variable.
·
An example of using a
local variable.
·
Good programming
practice requires the use of local
variables.
·
How professionally
developed programs use several programmers.
·
A review of breaking
a program down into smaller components.
·
An example of
problems encountered when global
variables are used.
·
An example of how to
correct the above problem through the use of local variables.
24. The string Object