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.