The magazine of the Melbourne PC User Group
Real Programming With JavaScript
Trevor Gosbell |
|
|
Trevor Gosbell takes learners further down that path of greater knowledge and a
deeper understanding of how to make computers work for you
|
For quite some time I have not had a high opinion of JavaScript. This is
probably because in the late 1990s I spent far too much time trying to get
so-called Dynamic HTML to work reliably on the version 4 flavours of Netscape
and Internet Explorer. And also because
JavaScript is far too often used in stupid and annoying ways on the Web. To name
a few: pop-up windows, window resizing, dialog boxes, cursor trails, and
JavaScript-only links and forms.
However, recently I have discovered that as with many other programming
languages, the power of JavaScript can be harnessed for good as well as evil.
JavaScript is a surprisingly powerful programming language and is well worth a
detailed look.
What is JavaScript?
It's a tired old refrain, but it bears repeating: JavaScript is NOT Java. It
seems the complication was deliberate but sadly misguided.
- Java is a full-featured compiled programming language developed by Sun
Microsystems. Java originally found popularity by providing extra functionality
to Web browsers in the form of "applets" -mini applications that could be run
inside Web pages. These days, Java typically finds more use in stand-alone
applications.
- JavaScript, orginally known as LiveScript, was developed by Netscape to allow
greater interaction between the Netscape browser and Java applets. It seems some
bright spark in the marketing pushed the name change to JavaScript and a
lifetime of confusion was born. It was not long before JavaScript was being
co-opted for use in the types of abuses mentioned above.
JavaScript is an object-oriented programming language commonly used to add
scripting features to Web browsers. Actually, that's slightly inaccurate — true
JavaScript is found in Netscape and related browsers (the Mozilla family), in
Internet Explorer the equivalent is JScript, and most modern graphical Web
browsers have scripting capabilities based on the standard ECMAScript.
Since 1997 the European Computer Manufacturers Association (ECMA) has main-
tained the ECMAScript specification for a standard Web client scripting
language. By adhering to this specification as a minimum, the makers of Web
browsers have been able to provide much improved cross-browser functionality in
scripting, although
JavaScript and JScript both add proprietary extensions to the basic standard.
But enough of this — the easiest way to find out what JavaScript is really like
is to have a bash at it.
The Easiest Programming Environment
If you've got a recent Web browser and a text editor, then you're ready to write
JavaScript. It couldn't be easier.
Listing 1 - example01.html
<html>
<head>
<title>JavaScript Example 01</title>
<script language="JavaScript">
<!--
// JavaScript can appear in the head section
//-->
</script>
</head>
<body>
<script language="JavaScript">
<!--
// JavaScript can appear in the body section
//-->
</script>
</body>
</html> |
In a Web browser, a JavaScript must be read from inside a Web page. See Listing
1 above for an example. This is a complete Web page with two complete JavaScripts
inside. Both the Web page and the JavaScripts produce no notable output, but it
shows the rules that apply: JavaScripts can appear in the <head> section or the
<body> section of a Web page and JavaScripts are contained inside <script> tags.
A common idiom is to enclose JavaScript code inside HTML comment tags:
<!--
(JavaScript code goes here)
//-->
This is for historical reasons - when JavaScript first appeared many browsers
did not recognise the <script> tag, and as a result all of the program code
would be printed to the browser window (not a desirable outcome!) The vast
number of browsers used these days recognise the <script> tag so the problem has
largely disappeared, but the programming practice remains.
The examples in this article show only the JavaScript code, so if you want to
try them out make sure you include all of the HTML code shown in Listing 1. You
can also download the complete examples from my Web page:
http://member.melbpc.org.au/~tgosbell/.
Example scripts in this article should be inserted into the <body> part of a Web
page.
To run the examples, simply load the example file into your Web browser - there
is no need to load it from a Web server, you may open it directly from your own
hard disk. If you want to re-run a program, simply click the reload button on
the toolbar of your browser.
Input - Output
Readers of my recent article on "Eight Things Programming Languages Do"
(PC Update, April 2004) will recall that input and output provide ways for
programs to communicate with the outside world. Let's look at some of the
options available for input and output in JavaScript.
The simplest is
window.alert(), which puts up a dialog box with a message and an
"OK" button. The next is
window.confirm(), which produces a dialog box with a
message, an "OK" button and a "Cancel" button. (For my money, these buttons
would have been better labelled as "Yes" and "No" -and on some Macintosh
browsers that's how they appear - but to the best of my knowledge you can't
alter the button labels.) The
window.confirm() dialog box produces (or
"returns") a value that can be stored in a variable: if the user clicks the "OK"
button the value is TRUE, and it's FALSE if the user clicks "Cancel". The third
method is
window.prompt(), also a dialog box with a message, a text input field,
an "OK" button, and a "Cancel" button. If the user clicks "OK", whatever they
typed into the input field is the value returned.
Listing 2
var visitorName = window.prompt( "What is your
name?", "" );
var proceed = window.confirm( "Are you ready to go further
with JavaScript " + visitorName + "?");
if ( proceed == true )
{
window.alert ("That's great " + visitorName);
} |
Listing 2 illustrates the use of three input/output methods in JavaScript.
Firstly, the variable
visitorName stores whatever the user typed in response to
the question "What is your name?" in the
window.prompt() dialog box (see
Figure 1). The next question appears in a
window.confirm() dialog box (see
Figure 2) and the value TRUE (for "OK") or
FALSE (for "Cancel") is stored in the variable proceed. If the user agrees that
they are ready to proceed, they are then given a short message of encouragement
in a
window.alert() dialog box (see
Figure 3).
|

Figure 1.
window.prompt() in Macintosh
Safari browser.
|
|

Figure 2.
window.confirm() in Macintosh
Safari browser.
|
|

Figure 3.
window.alert() in Macintosh Safari
browser.
|
Functions
In "Eight Things Programming Languages Do
- Part 2" (PC Update, May 2004), I wrote that a
function is a batch of programming instructions that can be used repeatedly.
Let's refine that definition a bit more. In
JavaScript (as in most other languages) a function may:
- receive zero, one or more arguments, and
- produce (or "return") exactly one value
The normal purpose of a function is to perform some actions on the argument(s)
that produces some result that becomes the returned value.
We have already seen some examples
of JavaScript functions. The function
window.confirm() takes as an argument a
string that is printed in the dialog box
as a message. The value returned by
window.confirm() is either TRUE or FALSE,
depending on what button the user clicks.
The function
window.prompt() takes two arguments: firstly, a message string like
the one used in
window.confirm(), and secondly a default value that is inserted
into the text input field in the dialog box. In Listing 2, the second argument
is "" - an empty string - but you can experiment by changing this to whatever
you like.
The window.alert() function is a rare exception. Although it takes one argument,
a message string just like window.confirm(), window.alert() does not return a
value.
Gotcha - Addition or Concatenation?
In Listing 2, you might have noticed that several values were joined by a plus
sign (+) to produce a single argument. For example, the expression
"Are you ready to go further with JavaScript " + visitorName + "?"
produces a question directed personally to the user. If the user entered the
name as "Sam", the single value passed to
window.confirm() would be "Are you ready to go further with JavaScript Sam?".
This is the process of "string concatenation".
One of the limitations of JavaScript is that the plus sign (+) is reused (or
"overloaded") as the operator for mathematical addition and as the operator for
concatenation. Look at Listing 3:
Listing 3
var firstNum = window.prompt("Input a
number", 0);
var secondNum = window.prompt("Input another number", 0);
var total = firstNum + secondNum;
window.alert(total); |
In this script the variable
firstNum holds a number received by the first input
box, and
secondNum holds the number entered in the second input box. Then these
two numbers are added together and held in variable total, which is output to
the screen in an alert box. If we input the number 11 into the first input box (firstNum)
and 22 into the second (secondNum), the value output in the alert box (total)
will be 33, right? Wrong! See Figure 4. |

Figure 4. Oops — that's not addition! |
Instead of adding 11 and 22, they have been joined together as if they were two
strings of characters "11" and "22". And as far as JavaScript is concerned, that
is what they are. The
window.prompt() function allows you to type anything at
the keyboard - not just numbers - so it must return a string.
Some languages (such as C and Java) are "strongly typed", that is when a
variable is declared the programmer must also indicate what type of data it will
contain (eg. string, integer, Boolean) and the variable can only hold values of
that type. Like other so-called scripting languages (such as Python and Perl)
JavaScript is "loosely typed". In this case variables are not restricted by data
type - in fact at different times in a program one variable may hold different
types of data.
Which brings us back to our problem - our two variables hold the values "11" and
"22" which we want to add as if they were numbers. The plus sign (+) only works
as mathematical addition if the values on both sides are numbers, otherwise it
works as concatenation (joining two strings). Clearly we need a way to convert
the values to numbers - fortunately JavaScript provides
it in the Number() function, as shown
in Listing 4:
Listing 4
var firstNum = window.prompt("Input a
number", 0);
var secondNum = window.prompt("Input another number", 0);
var total = Number( firstNum ) + Number( secondNum );
window.alert(total); |
The
Number() function takes a string value as an argument and tries to return it
as a number, which gives the desired result (see Figure 5). But Number() can't
perform miracles - it can't even turn the string "eleven" into the number 11.
The string passed into Number() must contain a recognisable number (postive or
negative, integer or decimal fraction), otherwise it will return the special
value NaN (short for Not a Number). You can put this to the test with the code
in Listing 4. |

Figure 5. JavaScript can do mathematics. |
DIY Functions
JavaScript allows us to declare our own functions, so let's make a prompt dialog
box that will only return numbers (Listing 5).
Listing 5
function numberPrompt( msg, dflt)
{
var errMsg = "Your answer must be a number - ";
var result = Number( window.prompt(msg, dflt));
while (isNaN(result))
{
result = Number(window.prompt(errMsg + msg,
dflt));
}
return result;
}
var firstNum = numberPrompt("Input a number", 0);
var secondNum = numberPrompt("Input another number", 0);
var total = firstNum + secondNum;
window.alert(total); |
To Dissect the Function:
var errMsg = "Your answer must be a number - ";
The variable
errMsg
holds a simple
error message that will be included in the dialog box if the user inputs a non-
numeric value.
var result = Number(window.prompt( msg, dflt ) );
The arguments to
numberPrompt() are passed onto an ordinary
window.prompt()
dialog box. The return value from
window.prompt() is converted to a number and stored in the result variable.
while (isNaN(result))
{
result = Number(window.prompt(errMsg + msg, dflt));
}
The while instruction is a repetition
instruction - it will repeat the instructions in the body of the loop inside the
curly brackets {} for as long as the condition
in brackets () is true. The condition -
isNaN( result ) - literally means "is result not a number?". If the answer to
this question is TRUE, then the body of the loop is evaluated and then the
condition is checked again. In this case the program will repeatedly prompt for
input until the user enters a number.
Hopefully it is clear that if the user enters a number in the first place, the
answer to the condition
isNaN(result) will be FALSE and the program will never
enter the body of the while loop.
return result;
At the end, tell the function what value to return.
The new
numberPrompt() function allows us to rewrite Listing 4. We can now be
sure that total will always be a number because
numberPrompt() will only return
numeric values to
firstNum and
secondNum.
Wrap-up
This introduction barely scratches the surface of what JavaScript has to offer
but I hope you are keen to explore and experiment further.
The input/output methods shown here are rudimentary and I would not normally (if
ever) recommend them for use on real live Web pages. However, they do provide
some quick-and-dirty ways to get information into and out of programs
while learning about JavaScript. In a later article we will explore some more
sophisticated input/output methods.
Reprinted from the June 2004 issue of PC Update, the magazine of Melbourne PC User Group, Australia
|