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