For best results: this site
requires that cookies be enabled for proper operation - see Legal Page for more info
Select Any of These
JAVA SCRIPT
YOUR FIRST JAVASCRIPT
It's time to move ahead and make JavaScript do something. Let's use
the language to write some words into an HTML document. We'll do that
with the write() method of the document object--but we'll worry about
the details later. For now, let's just try to get a feel for what
JavaScript programs look like. Particularly, let's see how they fit
into HTML documents.
Enter the following into a text document:
<HTML>
<HEAD>
<TITLE> A Simple JavaScript Program </TITLE>
</HEAD>
<BODY>
<P>Philosophy:
<SCRIPT LANGUAGE="JavaScript">
document.write("A blind man in a dark room looking for a black hat,
which is not there.")
</SCRIPT>
<P>That's JavaScript.
</BODY>
</HTML>
Save that as first.html. Load that file into your browser and note
what happens. We'll explore the reasons why in coming days.
THE SCRIPT.../SCRIPT TAGS
In the last tip, we created an HTML document that incorporated a
bit of JavaScript. In case you've just tuned in, or to refresh your
memory, here's the code:
<HTML>
<HEAD>
<TITLE> A Simple JavaScript Program </TITLE>
</HEAD>
<BODY>
<P>Philosophy:
<SCRIPT LANGUAGE="JavaScript">
document.write("A blind man in a dark room looking for a black hat,
which is not there.")
</SCRIPT>
<P>That's JavaScript.
</BODY>
</HTML>
Let's take a look at what's unusual there. Most of the HTML is
common
stuff, with the exception of the SCRIPT and /SCRIPT tags. These tags
delineate the portion of the document in which the JavaScript appears.
Everything outside the SCRIPT and /SCRIPT tags is HTML code;
everything inside them is JavaScript code. What's the
LANGUAGE attribute for?
THE LANGUAGE ATTRIBUTE
We've been exploring the syntax and function of the SCRIPT tags,
which
mark the beginning and end of passages of JavaScript code that are
embedded in an HTML document. But that's not all SCRIPT tags are for.
As it happens, the SCRIPT tags are used to denote scripts in other
languages. To accommodate this fact, the opening SCRIPT tag takes the
LANGUAGE attribute. The syntax looks like this:
<SCRIPT LANGUAGE="JavaScript">
This syntax is just like that of any other HTML tag that takes an
attribute. The name of the attribute is not case sensitive. In this
situation, "language" would have worked just as well as "LANGUAGE".
The value of the attribute--"JavaScript" in this case--must be
enclosed in quotation marks (double or single, as long as they're
consistent). The language name IS case sensitive. You have to specify
"JavaScript" and not "JAVASCRIPT" or "javascript".
----------------------------------------------
OTHER VALUES FOR THE LANGUAGE ATTRIBUTE
Most of the time, when you're writing JavaScript code and embedding
it
in HTML documents, you'll use a SCRIPT tag like this to open your
passages of code:
<SCRIPT LANGUAGE="JavaScript">
As you might imagine, the LANGUAGE attribute can take other values.
These include:
Of these, you'll use "VBScript" when writing VBScript code and
"JScript" when writing specifically to Microsoft's JavaScript-like
specification. The last two come in handy when you want to restrict
interpretation of your JavaScript code to browsers that understand
certain versions of the language. You'd do that only if your program
used some aspect of the language that isn't available in earlier
versions. For example, the switch statement, which we'll get to
shortly, is available only in JavaScript 1.2 and newer versions.
----------------------------------------------
THE DOCUMENT.WRITE() STATEMENT
We've been working on a program that, other than the opening and
closing SCRIPT tags that anchor it in a larger HTML document, consists
entirely of one line. Here it is:
<SCRIPT LANGUAGE="JavaScript">
document.write("A blind man in a dark room looking for a black hat,
which is not there.")
</SCRIPT>
The document.write() statement is an important part of this
program.
You'll see document.write() a lot. It causes the text that appears in
its parentheses to be written into the HTML document. The generalized
syntax is this:
document.write("Stuff to write.")
In this case, we're writing what's called a string literal, which
is a
passage of text that's explicitly stated in the code. When working
with string literals, you must enclose them in quotation marks (single
or double--it doesn't matter). Soon, you'll see how to use variables.
You can write variables with document.write() without the quotes. As a
matter of fact, you can't put quotes around variable names.
----------------------------------------------
UNDERSTANDING DOT SYNTAX
Let's look for a moment at document.write(). It's a reference to a
particular method of a particular object. The period--called a dot
here--separates the object name from the method name. This is called
dot syntax.
The dot is called an operator. Most of the time, we think of
operators
as mathematical and logical "verbs," such as +, -, *, and /. Those are
operators, of course, but so is the period in the document.write()
context. It separates the name of the object--document--from the name
of the method--write().
The parentheses that appear as part of document.write() are
customary.
Whenever you're talking about a method, follow it with a pair of empty
parentheses. Properties don't take the parentheses.
----------------------------------------------
HOW TO THINK ABOUT INTERPRETERS
In the simple program
<SCRIPT LANGUAGE="JavaScript">
document.write("A blind man in a dark room looking for a black hat,
which is not there.")
</SCRIPT>
it's proper to say that the document.write() statement writes the
phrase in the parentheses into the HTML document. What does that mean?
You have to think of the HTML interpreter (which acts on HTML code)
and the JavaScript interpreter (which looks at and executes JavaScript
code) as separate entities, which in fact they are. They complement
each other as they decide how an HTML document with embedded
JavaScript will be rendered. Here's the conceptual sequence:
1. The HTML interpreter looks at the document as a whole and
figures
out that there are passages of JavaScript, which will require the
JavaScript interpreter to come into play.
2. The JavaScript interpreter looks at and executes the passages of
JavaScript code (there can be more than one of them in a given
HTML/JavaScript document). The JavaScript may (and in the case of the
code above, does) yield a modified HTML document. This modified
document never exists in file form anywhere; it's just an intermediate
step in the client computer's memory.
3. The HTML interpreter comes back and interprets the modified HTML
document. The results of this interpretation are what appear in the
browser window.
So, in the case of this simple program, the document.write()
statement
writes the phrase into the intermediate HTML document, which is then
interpreted and rendered by the HTML interpreter. One neat effect of
this approach: You can use JavaScript to write HTML tags!
----------------------------------------------
SINGLE-LINE JAVASCRIPT COMMENTS
You'll want to supplement your JavaScript code with little
notations
in a human language such as English or German. These little notations,
called comments, help you and others figure out what different parts
of your program are for, long after your brain has moved on to new
problems. Think of comments as guideposts through the wilderness of
forgotten code.
The JavaScript language makes provisions for two kinds of comments.
The first, designated by //, tells the JavaScript interpreter to
ignore everything from the comment designator to the end of the line
on which it appears. Use this kind of comment to write little notes
that explain what particular lines of code are for. Here's an example:
document.write("I have not yet begun to fight.") //Writes a John
Paul
Jones quote to the HTML document.
Tomorrow: the second kind of comment.
----------------------------------------------
MULTILINE JAVASCRIPT COMMENTS
In the last tip, you learned how to create single-line JavaScript
comments with the // syntax. There's another kind of comment that's
useful for longer notations.
The second kind of comment tells the JavaScript interpreter to
ignore
everything from an opening /* sequence to a closing */ sequence, even
if the comment ends up spanning several lines. Here's how it looks:
/*
By Ruth Ann Krinklemeyer
All rights reserved, (c) 1999.
Contact krinkle@krinklemeyer.com
*/
See? You can put as many lines as you want between the opening and
closing comment markers.
----------------------------------------------
USING COMMENTS AS TROUBLESHOOTING TOOLS
One of the handiest applications of comments--particularly the
single-line kind--is in tracking down problems. Say you suspected that
a particular line of code was causing an error. You could "comment
out" the suspicious line and see if the error goes away. You'd do that
in this way:
// document.write("This is the suspicious line of code.")
Or, you can use the multiline comment syntax to make the JavaScript
interpreter ignore a whole series of lines.
----------------------------------------------
HIDING JAVASCRIPT
Not all browsers know how to interpret JavaScript. What happens
when a
JavaScript-ignorant browser encounters JavaScript code in one of your
Web pages?
The SCRIPT and /SCRIPT tags aren't a problem. Practically every
HTML
interpreter knows to ignore any HTML tags it doesn't recognize (a tag
is defined as any word contained in angle brackets). But what about
the lines of JavaScript code contained within the SCRIPT tags? As it
turns out, a browser that doesn't know how to interpret them as
JavaScript will just display them as plain text, and that's not
something you want at all.
Protecting the lines of JavaScript code between the SCRIPT and
/SCRIPT
tags from being viewed by an ignorant browser is the job of HTML
comments, which are distinct from JavaScript comments.
HTML comments look like this:
<!-- Stuff ignored by the HTML parser goes here. -->
How do those fit into the syntax of an embedded JavaScript program?
That's tomorrow's topic.
----------------------------------------------
FITTING HTML COMMENTS INTO JAVASCRIPT PROGRAMS
You can protect JavaScript code from being rendered as plain text
by
browsers that don't understand it through judicious use of HTML
comments. The opening HTML comment
<!--
goes right after the opening SCRIPT tag. The tag that closes the
HTML
comment
-->
goes immediately before the /SCRIPT tag. But there's a trick.
Because
the closing HTML comment tag appears inside the region that's supposed
to be handled by the JavaScript interpreter, it will cause an error if
that interpreter is allowed to see it. For that reason, we have to
protect closing HTML comment tags with a one-line JavaScript comment
indicator (//).
You may ask why the opening HTML comment tag doesn't also have to
be
protected by a JavaScript comment, since it also is inside the script
block. The fact is, the JavaScript interpreter knows to ignore opening
HTML comment tags. It doesn't know how to identify and ignore closing
HTML comment tags.
The whole assembly looks like this:
<SCRIPT LANGUAGE="JavaScript">
<!--
document.write("This browser has no trouble with JavaScript.")
// -->
</SCRIPT>
----------------------------------------------
TAKE A LOOK AT NOTETAB
There's an excellent shareware editor out there that's perfect for
JavaScript work. NoteTab has a lot to offer, regardless of the
language you're working in. In addition to its excellent
text-manipulation features, NoteTab allows you to apply regular
expressions to documents, run Perl scripts on documents, search and
replace across multiple files, and have ready access to libraries of
tags and keywords. There's also a very good macro-writing facility.
You can download the full-featured NoteTab Pro to use for a limited
time before paying a registration fee (which is a very fair $19.95 in
the U.S.). If you don't need all those features, there's a slightly
stripped-down version of the program (NoteTab Standard) for $9.95
(U.S.) and a useful version called NoteTab Light that's free. Check it
out for yourself at
http://www.notetab.com/
----------------------------------------------
STICKING CHARACTER SEQUENCES TOGETHER
You've seen how to write text into an HTML document with
document.write(), but did you know it's possible to stick multiple
words together in the parentheses and expect them to print out
together? In JavaScript, the "sticker" is the plus sign (+). It's
formally known as a string concatenator in this situation. If we have
this line of code:
document.write("New York" + "Yankees")
the result will be that New YorkYankees will be written into the
document when this line is interpreted. How do we avoid the
smashed-together look? Tune in for the next tip!
----------------------------------------------
DON'T FORGET YOUR SPACES
Yesterday, we saw that this line of code:
document.write("New York" + "Yankees")
yields this:
New YorkYankees
If you don't want the words to run together, you can do either of
these things:
document.write("New York " + "Yankees")
or
document.write("New York" + " " + "Yankees")
Either way, an extra space is added to the string between the two
portions of the team name.
----------------------------------------------
THE BASICS OF VARIABLES
The essence of programming in any computer language is assigning
values to variables and having the computer keep track of how those
values change during the course of program execution. Without
variables, any programs we write would be little more than automated
routines that consistently yield the same results.
There are rules, however, that govern the creation of variables.
Variables must be declared in a certain way. They must be given names
that fit certain specifications. They must be assigned values in
certain ways. That said, understanding variables isn't outrageously
complicated. Getting the gist of JavaScript variables is vastly easier
than understanding how variables work in, say, Java or C++. If you've
worked with those languages before, you'll find the flexibility and
adaptability of JavaScript variables to be a real blessing to speedy
program design.
----------------------------------------------
UNDERSTANDING VAR
Before JavaScript can do anything with variables--assign values to
them, much less manipulate those values--it needs to will those
variables into existence. The process of creating and giving names to
variables is called declaring variables. Variable declarations play a
critical role in any program, but fortunately, they're not hard to
understand and, in fact, they happen almost automatically. All you
need to know are a few simple rules about a special keyword--var--and
how to choose names for variables.
The most important point to remember about declaring variables is
that
you should always precede the first (and only the first) instance of a
new variable name with the keyword var. The keyword var tells the
JavaScript interpreter that whatever follows it is a variable, and so
a space in the computer's memory should be designated to hold whatever
contents are assigned to that variable in the future. That's what
variables really are, by the way--pieces of memory with names that the
JavaScript interpreter keeps track of.
You can create variables without var in many cases. JavaScript is
sufficiently smart and forgiving to allow that. Nonetheless, you
should always precede the first instance of a variable in JavaScript
with var. It's a good practice that can help you avoid problems.
----------------------------------------------
DECLARING A VARIABLE: THE FORMAL APPROACH
Let's consider the most formal way of setting up a variable for the
first time. Say we want a variable called Peas, and we want it to
contain a string: "round and green". We can do this very deliberately
in two lines of code. First, we use var to declare the variable:
var Peas
With that, Peas is made to exist. It is declared. All that line
does
is tell the JavaScript interpreter to reserve a space in memory and
assign the name Peas to it. In tomorrow's tip, we'll take the next
step: assigning a value to the variable.
----------------------------------------------
ASSIGNING A VALUE TO A VARIABLE
The key to assigning a value to a variable is the equal sign (=).
The
equal sign makes the variable name (to the left of the equal sign)
have the value of whatever is to the right of the equal sign (be it a
literal value, an expression that can be evaluated, or another
variable name). Here's how it looks:
Peas = "round and green"
The space in memory named Peas now contains the string "round and
green".
----------------------------------------------
A MORE COMPACT APPROACH TO VARIABLE DECLARATION AND ASSIGNMENT
Let's use a more compact declaration-and-assignment syntax to set
up a
variable called Potatoes. It gets declared and initialized in a single
line, like this:
var Potatoes = "oblong and brown"
That's a totally fine way to go about creating a variable. It's
more
compact than the two-line method. On the other hand, it's possible
(though unlikely, after a while) that you, in reviewing your
JavaScript code at a later date, could get confused by having
everything on one line and misunderstand what the program was up to.
It's a matter of personal preference.
----------------------------------------------
A DECLARATION AND ASSIGNMENT SHORTCUT
Now, let's use an abbreviated syntax. We can declare and initialize
a
variable on one line, without the use of var. Using this system, the
declaration and initialization statement for a variable called Carrots
looks like this:
Carrots = "long and orange"
That's a shortcut--JavaScript assumes that if you want to assign
the
value "long and orange" to Carrots, then Carrots must be a variable.
This syntax is used a lot, but it isn't good practice. In certain
situations, variables declared without var will cause problems. In
contrast, under no conditions will variables declared with var do
anything unwarranted. Stay on the safe side--always use var.
----------------------------------------------
OTHER VARIABLE-NAMING CONSIDERATIONS
Although JavaScript imposes some technical rules on variable names,
it's a good idea to assign names that describe what variables contain
and what they do. Later, if you want to modify your programs,
descriptive variable names will help you figure out what your
variables represent.
Single-character variables generally are a bad idea, except in
situations in which such variables are traditional and their meanings
will be generally understood. For example, in JavaScript loops (which
you'll learn about soon), it's customary to use the variable i as the
loop index. People who know how to program assume that this is the
function of variables named i.
A variable's scope is the portion of a program in which it exists.
You
can refer to a particular variable only in the portions of the program
that fall within the variable's scope. The rules for scope aren't
difficult to keep straight:
- If you declare a variable anywhere in the main portion of a
JavaScript program, then the variable and its contents are accessible
anywhere in the main body of the program.
- If you declare a variable in a function, then the variable and its
contents are accessible only within that function. Any attempt to
refer to the variable outside the function will result in an error
message from the JavaScript interpreter.
- If you declare a variable in a script block in the <HEAD> section of
your HTML document, the variable is said to be global and may be
accessed by any JavaScript code in that document. It may be referred
to (and changed) by any function or in code that appears in the <BODY>
section.
By creating functions, you'll move much of your hairy JavaScript
code
out of the bodies of your HTML documents. Declaring a function
involves putting an extra piece of JavaScript code in the <HEAD>
portion of your HTML document. To declare a function, you have to put
an extra set of <SCRIPT>...</SCRIPT> tags in the <HEAD> portion of the
HTML document. Inside that block, you have to declare each function
(you can declare as many as you need) like this:
function uniqueName()
{
// Function code goes here.
}
That is, you put the word function, followed by the name by which
you
want to refer to the function and a pair of parentheses, on one line.
You then surround the code that makes up the function with curly
brackets: { and }. In this example, the comment line takes the place
of any actual code.
----------------------------------------------
CALLING A FUNCTION
To refer to a function you've declared (which is to say, to execute
the code it contains), you refer to it by name. If you've declared a
function called multiply(), you could refer to it in the <BODY>
section of your HTML document just by using the word multiply(). Don't
forget those parentheses, since they're important. Any code in the
definition of multiply() in the <HEAD> section will run where that
reference, or "call," appears in the code.
Here's how the overall syntax looks:
<HTML>
<HEAD>
<SCRIPT LANGUAGE = "JavaScript">
function uniqueName()
{
// Function code goes here.
}
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE = "JavaScript">
uniqueName() /* Effects of the code in uniqueName() will be seen
here.
*/
</SCRIPT>
</BODY>
----------------------------------------------
DESIGNING A FUNCTION THAT TAKES STRING
Let's design a function that takes some string (a "string" is
programmer talk for any sequence of characters) and attaches HTML tags
to it. It will attach HTML <I> ... </I> tags to whatever we send it as
a parameter. Here's our code:
<HTML>
<HEAD>
<TITLE>AutoItalic</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function autoItalic(text)
{
//This function takes text and puts it into italic type.
document.write("<I>" + text + "</I>")
}
</SCRIPT>
</HEAD>
<BODY>
<H1>Here's a demonstration of AutoItalic.</H1>
//This script uses a function call to format some text.
document.write("<P>One of the books I'm reading is ")
autoItalic("Life and Death in Shanghai")
document.write(", by Nien Cheng. It's really outstanding.")
// Disengage cloaking. -->
</SCRIPT>
<H1>Cool, eh?</H1>
</BODY>
</HTML>
Save that as a file, load it in your browser, and see how the
italicized text shows up as if the tags were there all along.
----------------------------------------------
A JAVASCRIPT LIBRARY FOR NOTETAB
Loyal readers of the TipWorld JavaScript tips know about NoteTab,
an
excellent text editor that's well suited to JavaScript programming. If
this is the first you've heard of the program, check it out at
http://www.notetab.com
One of the program's main attractions is its extensibility. You can
write libraries--called clipbooks--that provide shortcuts for a
variety of purposes. A bunch of JavaScript clipbooks are available.
You'll find a list of them here:
http://www.notetab.com/clipbooks/java.htm
----------------------------------------------
WHAT CAN YOU PUT IN A VARIABLE?
JavaScript employs loose typing, which is a fancy way of saying
that
you can stick pretty much any value you want into any given variable.
There are four basic kinds of data (also known as data types) that you
can use. Here's a list:
- Number: You know what numbers are. To JavaScript, they're one of
several data types. Unlike other languages, JavaScript doesn't
distinguish among large and small numbers, or real numbers and
integers. The values 34.563, 45, and 3E23 (which is in exponential
notation) are all values of type number.
- String: A string is a sequence of characters. Examples of strings
include "Ferrets," "Hong Kong," "heffalumps and woozles," and even
"2001."
- Boolean: Named after George Boole, an English mathematician who
invented a system of algebra based upon true and false values, Boolean
variables can hold only true or false. They're handy for determining
whether certain conditions are true.
- Object: You'll learn about objects later, but understand for the
time being that objects are a special data type.
Remember scientific notation? You probably learned about it in high
school and perhaps promptly forgot it. Let's take a look at how
scientific notation--called exponential notation here--works.
In everyday writing, you might mention 4.5 x 10^6 (we have to use
the
caret [^] here because plain-text email can't handle real exponents).
That value refers to 4.5 million, or 4,500,000. The trick is to take
the decimal point as it appears in the exponential expression and move
it to the right six places (six being the exponent that follows the
10). Taking 4.5 and moving the decimal point six places to the right,
adding zeroes as you go, yields 4500000.
This works with negative numbers, too. The expression 4.5 x 10^-6
is
equivalent to 0.0000045. You take the decimal from the exponential
expression and hop it six places to the left, adding zeroes as you go.
JavaScript numbers can be in exponential format. We'll get into that
syntax next time.
----------------------------------------------
EXPONENTIAL NOTATION IN JAVASCRIPT
In exponential notation, this expression:
4.5 x 10^6
is read as "four-point-five times ten to the sixth" and is equal to
4,500,000. But JavaScript can't handle raised exponent notation. It
uses the letter E in place of the "times ten to the" part. Here are
valid exponential expressions:
4.5E6 // Equivalent to 4.5 x 10^6
4.5E-6 // Equivalent to 4.5 x 10^-6
----------------------------------------------
DISTINGUISHING SMALL VALUES FROM NEGATIVE ONES
When working with exponential notation in JavaScript, don't confuse
very small (but positive) values with negative values. Remember, the
value after the E is the exponent. Positive exponents indicate
movement of the decimal to the right; negative exponents indicate
movement of the decimal to the left. The exponent's sign has nothing
to do with whether the whole exponential expression is positive or
negative. The sign that indicates this goes out to the left, as
always. Here are some examples:
4.5E-6 // Equivalent to 0.0000045
4.5E6 // Equivalent to 4500000
-4.5E-6 // Equivalent to -0.0000045
-4.5E6 // Equivalent to -4500000
----------------------------------------------
UNDERSTANDING OCTAL NOTATION
Sometimes, you'll find that octal numbers (numbers based on a base
of
eight) are handy for doing certain calculations. Octal often comes
into play as a shorthand way of representing digital values.
JavaScript can handle octal numbers. They must begin with a leading
zero, like this:
var octalValue = 07231
However, be aware that when written, octal values are translated
into
decimal numbers. Without special procedures, JavaScript will accept
octal numbers only as input, and will generate all output in decimal
numbers.
JavaScript can take hexadecimal, or base-16, numbers as values for
its
variables. Hexadecimal numbers must begin with the sequence 0x or 0X
(that is, zero x or zero X). Here are some examples:
var hexValue1 = 0x4A
var hexValue2 = 0X9D45
As is the case with octal values, JavaScript normally translates
hex
values into decimal numbers when using them as output.
----------------------------------------------
USING ESCAPED CHARACTERS IN STRINGS
Sometimes, you'll want a quoted string to include a character that
you
can't use without causing an error in the JavaScript interpreter. For
example, if you wanted to do this:
testVar = "Cows go "moo" when they are content."
you'd get into trouble, because the interpreter would think the "
(quotation mark) before moo was there to terminate the string literal.
So, you would need to escape the quotation mark, like this:
testVar = "Cows go \"moo\" when they are content."
The \" sequence alerts the interpreter that the " doesn't terminate
the string, but is meant to be seen as a literal character. Other
useful escaped characters include the single quote (/'), the backslash
(\\), the newline (\n), and the carriage return (\r).
The great thing about JavaScript data types is that when it comes
to
assigning values to variables, they don't matter all that much. In
other languages, you have to designate a variable as a string and then
never use it for anything other than holding strings throughout the
program. In JavaScript, data types are fleeting things. A variable
contains data of a certain data type only until you set that variable
to a value of another data type.
So, a single variable you declare can hold a string for a while,
get
reassigned to hold a number, get assigned a Boolean value, and finally
be made to hold a string again. This is called loose typing.
----------------------------------------------
THE BASICS OF OPERATORS
Sooner or later, you're going to want to perform operations upon
values. That's why there is a special class of words and characters
called operators. Operators perform specific actions upon values.
You're probably familiar with operators from everyday math: plus (+)
is an operator that adds two numbers (or the contents of two
variables), like this:
2 + 3
or this:
x + r + 5
Fortunately, many everyday operators work the same way in
JavaScript
as they do in the real world. There are some new, perhaps obscure,
operators too. We'll explore a handful of them in the days to come.
----------------------------------------------
GETTING TO KNOW THE BASIC ARITHMETIC OPERATORS
The four basic arithmetic operations are addition, subtraction,
multiplication, and division. The operations work exactly as they do
in elementary arithmetic as performed on paper, though a couple of the
operators may seem unfamiliar. Addition and subtraction are
represented by the plus (+) and minus (-) signs, respectively.
Multiplication and division are denoted by the asterisk (*) and
forward slash (/), respectively. Here's how the operations look in
code:
result = 8 * 5
// Variable result holds 40
result = 8 / 5
// Variable result holds 1.6
result = 8 - 5
// Variable result holds 3
result = 8 + 5
// Variable result holds 13
----------------------------------------------
TRYING OUT THE ARITHMETIC OPERATORS
Here's a little program that demonstrates how the various operators
work in practice.
<HTML>
<HEAD>
<TITLE> Arithmetic Operators </TITLE>
</HEAD>
<BODY>
<H1> What Fun JavaScript Arithmetic Can Be! </H1>
<SCRIPT LANGUAGE="JavaScript">
<!--
var Vinegar = 5
var Oil = 3
var Result
document.write("<H2>The Plus Operator</H2>")
Result = Vinegar + Oil
document.write("The sum of " + Vinegar + " plus " + Oil + " is " +
Result + ".")
document.write("<H2>The Minus (-) Operator</H2>")
Result = Vinegar - Oil
document.write("The result of " + Vinegar + " minus " + Oil + " is " +
Result + ".")
document.write("<H2>The Multiplication (*) Operator</H2>")
Result = Vinegar * Oil
document.write("The result of " + Vinegar + " times " + Oil + " is " +
Result + ".")
document.write("<H2>The Division (/) Operator</H2>")
Result = Vinegar / Oil
document.write("The result of " + Vinegar + " divided by " + Oil + "
is "
+ Result + ".")
document.write("<H2>The Modulo (%) Operator</H2>")
Result = Vinegar % Oil
document.write("The result of " + Vinegar + " modulo " + Oil + " is "
+
Result + ".")
// -->
</SCRIPT>
</BODY>
</HTML>
This program declares three variables (Vinegar, Oil, and Result)
and
performs all five of the JavaScript arithmetic operations on them
(addition, subtraction, multiplication, division, and modulo). Note
that the values of Oil and Vinegar never change--the results of the
operations are always placed in Result, which gets printed out before
it gets altered again.
----------------------------------------------
A NEW BOOK OF INTEREST
O'Reilly & Associates, publishers of many excellent books on
JavaScript and other technical topics, has come out with a new
JavaScript book. Entitled JavaScript Application Cookbook, the book
promises to provide JavaScript developers with reusable code for a
variety of complex jobs. This sort of approach makes a lot of
sense--once you have the basics of the language in mind, you'll want
to use prewritten code as much as possible for large jobs.
Here are the details:
JavaScript Application Cookbook
By Jerry Bradenbaugh
ISBN 1-56592-577-7
You have seen that the + operator can be used to stick strings
together. More recently, you saw that the plus operator can serve a
mathematical purpose, adding numbers together. That's okay, because +
is said to be overloaded. That is, it does different things in
different situations. When faced with two strings, it concatenates
them. When faced with two numbers, it sums them. For this reason, you
have to be careful what kind of information you give the + operator to
work with.
----------------------------------------------
AN ADDITION AND ASSIGNMENT SHORTCUT WITH +=
One of the things you'll have to do most frequently in your
JavaScript
programs is assign the value of a variable or a constant to another
variable. You've already done this several times with the equal sign
(=), so you understand its functioning.
More interestingly, the equal sign has some exotic relatives.
They're
shortcuts, really. Take += for example. It works like this:
x = x + 2
is the same as
x += 2
See? The += operator saves you some programming keystrokes. You
just
put the variable you want to change on the left of the += sign, put
the value you want to add to the changing variable to the operator's
right, and you're done.
----------------------------------------------
OTHER COMBINED ARITHMETIC AND ASSIGNMENT OPERATORS
You've seen that it's possible to combine an addition operation
with
an assignment operation using the += operator. For example,
t=7 t += 5
results in t holding 12. There are other operators like this, one
for
each of the arithmetic operations. Here's a list:
This program is a demonstration of JavaScript's combined operators.
See how the variable Wizard is declared, then repeatedly set (with the
= assignment operator) to contain the value 3? In each case, the
program sets Wizard to 3, applies a different assignment operator to
it, and displays the results in the HTML document.
----------------------------------------------
USING THE INCREMENT OPERATOR
Often, you'll find it necessary to add 1 to a variable's value. In
fact, you'll do this a lot when working with loops. You can do it this
way:
i = i + 1
or this way:
i += 1
But there's an even faster way. This also is equivalent to the two
examples above:
i++
The increment operator (++) adds 1 to the variable to which it
applies. It's that easy.
----------------------------------------------
USING THE NEGATION OPERATOR
JavaScript variables can handle negative numbers, but you also can
use
the minus sign (-) as an operator to invert the result of some
arithmetic operation. That is, you can use the minus sign to turn
negative results into positive results and positive results into
negative ones. Say you had this code in your program:
result = (8 - 19)
That results in result holding the value -11, which is of course a
negative number. Say, however, that you put the negation operator into
play, like this:
result = (-(8 - 19))
That would result in result holding 11, which is the negation of
the
result of the subtraction operation.
----------------------------------------------
TAKING A LOOK AT THE COMPARISON OPERATORS
When you compare values to one another, you want a concise
statement
of the relationship that exists between the values. JavaScript
provides several operators that look at values and return a Boolean
result, depending upon the values. These are called comparison
operators. The "is equal to" operator (==) is typical. Say you have
this statement:
relationship = (7 == 8)
That results in relationship holding the Boolean value false,
because
7 is not equal to 8. Here is a complete list of the comparison
operators:
Is equal to (==)
Is not equal to (!=)
Is greater than (>)
Is less than (<)
Is greater than or equal to (>=)
Is less than or equal to (<=)
----------------------------------------------
A TRICK FOR COMPARISON OPERATORS
There's a trick to remembering the behavior of some of the
comparison
operators. You may or may not have learned this trick in grammar
school. If you did learn it, you may have tried to forget it for its
sheer silliness. But it works, so pay it some heed.
Think of the < and > characters as alligator mouths. The alligator
always wants to eat the most possible, so his open mouth always faces
the larger number. Extra bonus note for the Australians in the
audience: An alligator is a lot like a crocodile, mouth-wise.
----------------------------------------------
SEEING COMPARISON OPERATORS IN ACTION
Here's a program that shows how the comparison operators yield
different Boolean values under different conditions. Just cut this
out, paste it into a text file, save that file as HTML, and load the
HTML file into your browser.
<HTML>
<HEAD>
<TITLE> Comparison Operators </TITLE>
</HEAD>
<BODY>
<H1> Comparison Operators! What Fun! </H1>
<SCRIPT LANGUAGE="JavaScript">
<!--
var One = 5
var Two = -3
var Three = 5
var Truth
document.write("<H2>The Equals (==) Operator</H2>")
Truth = (One == Two)
document.write("<P>" + One + " == " + Two + " yields " + Truth + ".")
Truth = (One == Three)
document.write("<P>" + One + " == " + Three + " yields " + Truth +
".")
document.write("<H2>The Does Not Equal (!=) Operator</H2>")
Truth = (One != Two)
document.write("<P>" + One + " != " + Two + " yields " + Truth + ".")
Truth = (One != Three)
document.write("<P>" + One + " != " + Three + " yields " + Truth +
".")
document.write("<H2>The Greater Than (>) Operator</H2>")
Truth = (One > Two)
document.write("<P>" + One + " > " + Two + " yields " + Truth + ".")
Truth = (One > Three)
document.write("<P>" + One + " > " + Three + " yields " + Truth + ".")
Truth = (Two > One)
document.write("<P>" + Two + " > " + One + " yields " + Truth + ".")
document.write("<H2>The Less Than (<) Operator</H2>")
Truth = (One < Two)
document.write("<P>" + One + " < " + Two + " yields " + Truth + ".")
Truth = (One < Three)
document.write("<P>" + One + " < " + Three + " yields " + Truth + ".")
Truth = (Two < One)
document.write("<P>" + Two + " < " + One + " yields " + Truth + ".")
document.write("<H2>The Greater Than or Equal to (>=)
Operator</H2>")
Truth = (One >= Two)
document.write("<P>" + One + " >= " + Two + " yields " + Truth + ".")
Truth = (One >= Three)
document.write("<P>" + One + " >= " + Three + " yields " + Truth +
".")
Truth = (Two >= One)
document.write("<P>" + Two + " >= " + One + " yields " + Truth + ".")
document.write("<H2>The Less Than or Equal to (<=) Operator</H2>")
Truth = (One <= Two)
document.write("<P>" + One + " <= " + Two + " yields " + Truth + ".")
Truth = (One <= Three)
document.write("<P>" + One + " <= " + Three + " yields " + Truth +
".")
Truth = (Two <= One)
document.write("<P>" + Two + " <= " + One + " yields " + Truth + ".")
// -->
</SCRIPT>
</BODY>
</HTML>
This program makes clear the fact that the result of a comparison
operation is a Boolean value: true or false. By declaring three
variables, two of which have the same value and one of which has a
different value, the program gives the comparison operators material
to work with.
Often, you'll want to do two or more comparison operations and
evaluate them as a group. If all the comparisons come out true, you
may want to do one thing. If none of the comparisons come out true,
you may want to do something else. If some, but not all, of the
comparisons come out true, you may want to have your program do a
third thing.
Logical operators give you the ability to evaluate multiple Boolean
expressions--multiple true and false values. JavaScript has three
Boolean operators. The operators are AND (&&), OR (||), and NOT (!).
Next time, we'll see how these operators work.
----------------------------------------------
LOOKING AT LOGICAL OPERATORS
The basic idea behind the logical operators AND (&&) and OR (||) is
that they evaluate two Boolean values. In the case of AND, the logical
operation returns true if both the value to the operator's left and
the value to its right are true. The OR operator returns true if
either or both of its operands are true, returning false only when
both operands are false.
The NOT (!) operator is a unary operator, almost exactly like
negation
(-) in arithmetic. The NOT operator takes a Boolean value and converts
it to the other Boolean value.
Here's a program that shows how the logical operators work:
<HTML>
<HEAD>
<TITLE> Logical Operators </TITLE>
</HEAD>
<BODY>
<H1> My Kingdom for a Logical Operator! </H1>
<SCRIPT LANGUAGE="JavaScript">
<!--
var OnePotato = true
var TwoPotato = false
var ThreePotato = true
var FourPotato = false
var Truth
document.write("<H2>The AND (&&) Logical Operator</H2>")
Truth = (OnePotato && TwoPotato)
document.write("<P>When you compare " + OnePotato + " and " +
TwoPotato +
" with the AND (&&) logical operator, you get " + Truth + ".")
Truth = (OnePotato && ThreePotato)
document.write("<P>When you compare " + OnePotato + " and " +
ThreePotato
+ " with the AND (&&) logical operator, you get " + Truth + ".")
document.write("<H2>The OR (||) Logical Operator</H2>")
Truth = (TwoPotato || FourPotato)
document.write("<P>When you compare " + TwoPotato + " and " +
FourPotato +
" with the OR (||) logical operator, you get " + Truth + ".")
Truth = (OnePotato || TwoPotato)
document.write("<P>When you compare " + OnePotato + " and " +
TwoPotato +
" with the OR (||) logical operator, you get " + Truth + ".")
document.write("<H2>The NOT (!) Logical Operator</H2>")
Truth = ! OnePotato
document.write("<P>When you apply the NOT logical operator to " +
OnePotato + ", you get " + Truth + ".")
Truth = ! TwoPotato
document.write("<P>When you apply the NOT logical operator to " +
TwoPotato + ", you get " + Truth + ".")
// -->
</SCRIPT>
</BODY>
</HTML>
----------------------------------------------
USING THE TYPEOF OPERATOR TO CHECK DATA TYPE
As you know, JavaScript has loose typing. That means you can assign
values of any data type (number, string, Boolean or object) to any
variable. The dark side of that blessing is that we're never
absolutely sure what kind of value a particular variable holds. We can
check, though. JavaScript gives us a special operator for this
purpose. The operator is called typeof, and yes, it's an operator even
though it's six characters long.
The typeof operator works like this:
typeof variableName
This statement yields a string as a result. The string is the
plain-English name (either number, string, Boolean, object, or
undefined) for the data type of the variable's value.
----------------------------------------------
GETTING A HANDLE ON OPERATOR PRECEDENCE
What happens when JavaScript encounters the following expression?
Result = 10 + 10 / 5
You may expect Result to evaluate to 4 after that expression
executes.
In fact, Result will evaluate to 12, because JavaScript carries out
certain operations before others. This sequence for handling
operations is called operator precedence.
Remember operator precedence for arithmetic operations by thinking
of
My Dear Aunt Sally. The letters that start those
words--MDAS--represent the correct order of operations for arithmetic
(multiplication, division, addition, and subtraction). There's more to
precedence than this, though. That's the stuff of the next tip.
----------------------------------------------
THE COMPLETE PRECEDENCE LIST
Here's the complete order in which operations are carried out in
JavaScript, from first to last. Don't worry if you don't understand
what all the operations mean--you'll learn about them later. They're
mentioned here so you can see where they fit into the precedence
scheme.
Values in parentheses, from innermost to outermost
Array index values
Function calls
NOT (!)
Bitwise NOT (~)
Negation (-)
Increment (++)
Decrement (--)
Multiplication (*)
Division (/)
Modulo (%)
Addition (+)
Subtraction (-)
Bitwise shifts (<<, >>, and >>>)
Comparison operators (<, <=, >, and >=)
Equality operators (== and !=)
Bitwise AND (&)
Bitwise XOR (^)
Bitwise OR (|)
AND (&&)
OR (||)
Conditionals (?)
Assignments (=, +=, -=, *=, /=, %=, <<=, >>=, >>>=, &=, ^=, and |=)
Commas
----------------------------------------------
NESTING IF STATEMENTS IN OTHER IF STATEMENTS
Here's how you might format a pair of nested if statements:
if (speed > 40)
{
if (rpm < 150)
{
document.write("Get it in gear!")
}
}
In this example, the document.write() statement will execute only
if
both (speed > 40) and (rpm < 150) are true. That's because the "inner"
if statement comes into play only if the "outer" if statement's
conditional evaluates to true; otherwise, the second if statement is
skipped altogether.
----------------------------------------------
INTRODUCING OTHERWISE STATEMENTS WITH MULTIPLE IFS
Sometimes, you'll want to have a JavaScript program do one thing if
a
condition is true and something else if it's not true. You could do
this with multiple if statements, like this:
if (condition)
{
// Code to execute if condition is true.
}
if (!(condition))
{
// Code to execute if condition is NOT true.
}
>From a syntactical standpoint, this code is totally legal and it
works. However, there are only certain times when this construction is
the right one to use, and you should keep it in mind should you ever
need it. But this construction is actually too long, which means
there's a better (shorter) way--which we'll get to next time.
JavaScript provides a way to react to multiple conditions without
using several if statements in sequence. This programming tool is
called the if...else statement. It looks like this:
if (condition)
{
// Code to execute if condition is true.
}
else
{
// Code to execute if condition is NOT true.
}
----------------------------------------------
IF...ELSE STATEMENTS AT WORK
Here's a little program that shows how if...else statements work in
practice.
<HTML>
<HEAD>
<TITLE>Cause and Effect</TITLE>
</HEAD>
<BODY>
<H1>Look at what prints below.</H1>
<SCRIPT LANGUAGE="JavaScript">
<!--
//This script reacts to the value of the variable Phil, which changes.
Phil = 5
document.write("<P>The value of Phil is now " + Phil + ".")
if (Phil == 5)
{
document.write("<P>This will print only if Phil is equal to
5.")
}
else
{
document.write("<P>This will print only if Phil is not
equal to 5.")
}
Phil = 152
document.write("<P>The value of Phil is now " + Phil)
if (Phil == 5)
{
document.write("<P>This will print only if Phil is equal to
5.")
}
else
{
document.write("<P>This will print only if Phil is not
equal to 5.")
}
// -->
</SCRIPT>
<H1>Control statements will change your life.</H1>
</BODY>
</HTML>
Now, to decipher the code:
1. In the first case, Phil is equal to 5, so the "if" portion of
the
first if...else statement runs.
2. In the second case, Phil is equal to something other than 5 (it's
152), and so the "else" block gets called.
3. That's all there is to it.
----------------------------------------------
ALL ABOUT LOOPS
Computers are very good at doing things over and over and over and
over--sorry--again. Repetition is not a chore for computers. All you
have to do is give the word, and a computer running a JavaScript
program will repeat the same procedure as many times as you want. It
will even repeat the procedure until a condition is satisfied--and
that condition may be, for example, that some problem has been solved.
A control structure that allows the repetition of a process in a
computer program is called a loop. A loop that runs the same piece of
code repeatedly is said to be looping the code. A single pass through
a loop and the code it contains is called an iteration of the loop.
----------------------------------------------
INTRODUCING FOR AND WHILE LOOPS
The two most common JavaScript loops are the for and while loops.
The
for loop repeats something a given number of times. For example, let's
say you want to print out the "99 Bottles Of Beer" song, a process
that involves 99 identical steps. Or, you might want to do
calculations for each year of a person's life.
A while loop, on the other hand, does something until a condition
is
met. You might not know how many times you'll have to do something
before that condition is met, but you know you'll want to stop when
the condition is true.
----------------------------------------------
LOOKING AT THE FOR LOOP'S SYNTAX
The generalized syntax of the for loop in JavaScript looks like
this
(pay attention, because the syntax is the same in Perl, C, Java, and
lots of other languages):
for (initialValue; test; incrementor)
{
// Code to be repeated goes here.
}
Here's what the values in the parentheses mean:
initialValue: the value of the index variable when execution of the
loop starts.
test: a Boolean expression that, when found to be false, causes
iteration of the code in the loop to halt.
incrementor: an arithmetic expression that changes the value of the
index variable at the start of each iteration of the loop.
----------------------------------------------
THE FOR LOOP IN ACTION
The best way to get a feel for a for loop is to see one go. Here's
a
little program that shows how such a loop works. Feel free to copy
this into a text file and load it into your browser.
<HTML>
<HEAD>
<TITLE>For You!</TITLE>
</HEAD>
<BODY>
<H1>Look at what prints below.</H1>
<SCRIPT LANGUAGE="JavaScript">
<!--
/* This script runs through a for loop. It prints the value of the
index and, to illustrate that you can do other things inside loops, it
multiplies the index by 10 and prints the result of that calculation.
*/
for (i = 1; i <= 10; i++)
{
demonstrator = 0
document.write("The value of i is now " + i + "." + "<BR>")
demonstrator = i * 10
document.write("The value of demonstrator is now " +
demonstrator + "."
+ "<BR>")
}
// -->
</SCRIPT>
<H1>Control statements will change your life.</H1>
</BODY>
</HTML>
----------------------------------------------
LOOKING MORE CLOSELY AT THE FOR LOOP SYNTAX
For loops depend on some of the least logical JavaScript code we've
seen to date. You're going to have to memorize the syntax for this
code. Here it is:
for (i = 1; i <= 10; i++)
Here's what it means. The word "for" is a keyword, indicating that
this line of code defines a for loop that acts upon the statements
enclosed in braces, which follow. The stuff in the parentheses defines
how long the for loop goes on and how it operates. Specifically:
i = 1: This defines the initial value of the index variable, i.
i <= 10: This defines the condition that's checked each time the loop
statements execute.
i++: This unary operation adds 1 to i each time the loop executes.
----------------------------------------------
HOW THE INTERPRETER THINKS ABOUT FOR LOOPS
If you've been following along the past few days, you know we've
been
looking at a for loop whose first line looks like this:
for (i = 1; i <= 10; i++)
The JavaScript interpreter comes to that for statement and thinks,
"Ah. A for loop. I should establish a variable called i and set it
equal to 1. Then, I should verify that 1 is less than or equal to 10
and, if it is, I should execute the four lines of JavaScript code in
the braces that follow the for statement."
The JavaScript interpreter then continues: "After doing that once,
I
should add 1 to i (that's what i++ means), giving i the value 2. Then,
I should re-evaluate (i <= 10) and if it comes out true, I should run
the four lines of brace-enclosed code again. I should repeat this
process until I get a value for i that is greater than 10."
Following that logic, the program runs the four lines of
brace-enclosed code ten times, once for each value of i from 1 to 10,
inclusive.
----------------------------------------------
SOME WELL-WRITTEN JAVASCRIPT BOOKS
If you haven't yet had the pleasure of reading Peachpit Press's
Visual
QuickStart Guides, by all means start now. They're excellent learning
aids, well designed and well written--and the books in this series
cover several subjects. The best of the bunch may be Elizabeth
Castro's "HTML 4 For The World Wide Web: Visual QuickStart Guide,"
which certainly makes worthwhile reading for JavaScript programmers.
Go to
Another member of the series that is of more obvious interest:
"Javascript For The World Wide Web: Visual QuickStart Guide," by Tom
Negrino and Dori Smith. This one explains all the key features clearly
and concisely--you'll learn a lot from it. Go to
----------------------------------------------
WHY WE USE THE LETTER I
If you've been reading these tips for a while, you've undoubtedly
noticed that when I need a good index variable for a loop, I use the
letter "i." Why "i"? No, that's not an existentialist imponderable. So
why do we usually use a variable named i as the index variable of
loops, and are we required to do so?
The variable i traditionally is used as the index variable of
loops,
probably as an abbreviation for "index." You can use whatever variable
name you want, though. The name "index" might be a good one; or maybe
"counter," if it helps you remember what the variable does.
----------------------------------------------
INTRODUCING WHILE LOOPS
In addition to the for loop, which we've discussed in previous
tips,
there's another kind of loop in JavaScript: the while loop. With while
loops, you can have the JavaScript interpreter repeatedly carry out a
series of instructions until a certain condition (or set of
conditions) is met. Unlike for loops, which execute their statements a
specific number of times and then move on, while loops will keep going
forever until their exit conditions are met.
Because while loops can drag on forever, the trick is to make sure
that the interpreter can get out of them at some point. If you're not
careful that the exit condition is always met sooner or later (even if
the interpreter faces a weird situation), you run the risk of getting
your program into an infinite loop--a loop that keeps going forever,
effectively causing a crash.
----------------------------------------------
WHILE LOOPS: GENERAL SYNTAX
The general syntax for while loops looks like this:
while (condition)
{
// Code to be executed repeatedly while condition is true.
}
As with an if statement, you must put a Boolean statement in place
of
condition above.
----------------------------------------------
AN EXAMPLE OF A WHILE LOOP
Here's a practical example of a while loop. Let's look at it by
first
pasting the following code into a new text document and viewing it
with a Web browser.
<HTML>
<HEAD>
<TITLE>While you were out...</TITLE>
</HEAD>
<BODY>
<H1>Look at what prints below.</H1>
<SCRIPT LANGUAGE="JavaScript">
<!--
/* This script runs through a while loop. It prints the value of
the
index and, to illustrate that you can do other things inside loops, it
multiplies the index by 10 and prints the result of that calculation.
*/
i = 1
while (i <= 10)
{
demonstrator = 0
document.write("The value of i is " + i + "." + "<BR>")
demonstrator = i * 10
document.write("The demonstrator's value is " + demonstrator
+ "." +
"<BR>")
i++
}
// -->
</SCRIPT>
<H1>Control statements will change your life.</H1>
</BODY>
</HTML>
See what happened? This program does precisely the same thing as
the
for loop we saw a few tips ago. It just goes about it in a different
way.
----------------------------------------------
HOW THE INTERPRETER THINKS ABOUT WHILE LOOPS
As you regular readers will recall, we've been considering this
while
loop:
i = 1
while (i <= 10)
{
demonstrator = 0
document.write("The value of i is " + i + "." + "<BR>")
demonstrator = i * 10
document.write("The demonstrator's value is " + demonstrator +
"." +
"<BR>")
i++
}
Now, let's step into the JavaScript interpreter's stream of
consciousness and listen to what it's thinking, starting at the i = 1
statement.
"Okay, the variable i is now equal to 1. Next line. Oh, a while
loop.
Okay. I am to execute the statements in the braces that follow the
while loop as long as i is less than or equal to 10. Let's
check--okay, i is equal to 1 now, and 1 is less than 10. Let's run
through those braced statements.
"Okay, so I am to create a variable called demonstrator and set it
to
0. This is not necessary, but it is good programming practice. Next
line. I use document.write() to display some text and the value of i.
Next line. I set demonstrator equal to the value of 10 times i. That's
10. So demonstrator is now 10. Next line. Again, I use
document.write() to print some text and the value of demonstrator into
the HTML document. Next line. I am to add 1 to the value of i, so i
now holds the value 2. I return to the while statement at the top of
the braces.
"I evaluate the statement (i <= 10). Since i now holds the value of
2,
(i <= 10) is true. So I run through the four braced statements again,
then return to the top and evaluate (i <= 10) once more. I'll keep
going through the braced statements until i equals 11."
----------------------------------------------
KNOWING WHEN TO TAKE A BREAK
You'll often want to break out of a for loop (or less often, a
while
loop) before the loop has completed all of its iterations.
Consider a simple problem: Using a for loop, find a number between
1
and 10 that can be multiplied by 10 to equal 50. Of course, the answer
is 5. But an unmodified for loop requires you to test 6, 7, 8, 9, and
10, even after you've found the answer.
The break statement fits into a loop (the statement works with
while
loops as well as with for loops) to stop the looping before the ending
condition (as specified in the first line of the loop) is satisfied.
----------------------------------------------
BREAK STATEMENTS AT WORK
Here's a program that shows how a break statement works. This
program
searches for a number between 1 and 10, which, when multiplied by 10,
equals 50. When the program finds that number, it simply stops looking
(via break):
<HTML>
<HEAD>
<TITLE>Take a Break</TITLE>
</HEAD>
<BODY>
<H1>Look at what prints below.</H1>
<SCRIPT LANGUAGE="JavaScript">
<!--
/* This script runs through a for loop until it finds a value that,
when multiplied by 10, equals 50. It then uses the break statement to
get out of the loop. */
for (i = 1; i <= 10; i++)
{
demonstrator = 0
document.write("The value of i is now " + i + "." + "<BR>")
demonstrator = i * 10
document.write("Variable demonstrator is now " + demonstrator
+ "." +
"<BR>")
if (demonstrator == 50)
{
document.write("<BR>")
document.write("I found it! " + i + " becomes 50 when
multiplied by 10!")
document.write("<BR>")
break
}
}
document.write("<BR>")
document.write("See what happened? The loop stopped when i got to 5.")
// -->
</SCRIPT>
<H1>Control statements will change your life.</H1>
</BODY>
</HTML>
----------------------------------------------
EXAMINING BREAK MORE CLOSELY
Let's revisit the for loop you saw a couple of exercises ago, and
take
a look at some new code we've added. Without the new code, the loop
would just print values for i and demonstrator from 1 to 10 and 10 to
100, respectively. Here's the code we've added:
if (demonstrator == 50)
{
document.write("")
document.write("I found it! " + i + "
becomes 50 when multiplied by 10!")
document.write("")
break
}
That's an if statement, of course. The code inside the if
statement's
braces executes only in the event that demonstrator (which, as you can
see in the code, is equal to i times 10) is equal to 50.
Most of what executes when demonstrator equals 50 is a series of
boring document.write() statements that declare the program has found
a value that equals 50 when multiplied by 10. But there's something
new: the break statement.
The break keyword tells the JavaScript interpreter to abandon the
loop
and move to the first line of code following the loop's braces. In
this case, it skips the iterations of loop for i=6 through i=10 and
moves right to the code that follows the for loop.
----------------------------------------------
WHAT BREAK DOES IN NESTED LOOPS
If you've constructed a series of nested loops, one break statement
will kick program execution back to the next highest loop. It will not
break out of all the nested loops. In the following example, the inner
loop will execute only five times with each of the 15 iterations of
the outer loop.
for (i = 1; i 5 break
}
}
----------------------------------------------
TODAY: A Recursive Program
by David Wall
Understanding recursion becomes easier when you study some
examples. With that said, let's dive into a program that uses
recursion to calculate the factorial of various numbers. Remember,
the factorial of a number -- n in this example -- is:
n! = n * (n-1) * (n-2) * ... * (1)
Now, on with the program.
Look what recursion can do for you!
--------------------------------------------------------------------------------The
factorial of 10 is
3628800.--------------------------------------------------------------------------------The
factorial of 5 is
120.--------------------------------------------------------------------------------The
factorial of 1 is
1.--------------------------------------------------------------------------------The
factorial of 0 is
1.--------------------------------------------------------------------------------
Recursion is magical...
- Analysis -
The interesting part of the program created here is the factorial.
Let's take another look at it, and then examine more closely what
it does:
function factorial(number)
{
//This function uses recursion to calculate factorials.
if (number > 0)
{
return number * (factorial(number - 1))
}
else
{
return 1
}
}
The function uses an if...else statement to determine the
conditions under which factorial gets called from within itself. If
factorial() is sent a number that is equal to or greater than 1, it
sends the number, minus one, to factorial() again and uses the
result in the multiplication.
Eventually, an iteration of factorial() will send 0 to another
iteration of factorial(). In that case, the else statement takes
over, the value 1 gets returned, and the iteration of factorial()
that sent 0 will be able to figure out what it should return to the
iteration that sent 1, and so on, back up to the iteration that
sent the original number to the first iteration of factorial().
I know -- recursion is confusing. To understand it better, try
making a chart of all the called instances of factorial() and the
values returned by each of them. Just keep in mind that the
if...else statement controls the flow of data through multiple
layers of function calls.
TODAY: Using Forms with JavaScript.
by David Wall
JavaScript excels at using forms to get information from Net
surfers; you can do whatever you wish with that information. Much
of what you do with JavaScript will have to do with forms and
the information that people enter into them.
You might use a form as a front-end for a program that does some
processing on a string someone enters. Or, you might use forms to
create a calculator that runs user inputs through a special
formula. When you're ready to tackle really advanced JavaScript
topics, you can use forms to preprocess information before it gets
sent to a CGI script or other server-side routine. Essentially,
it's through forms that Web surfers interact with your JavaScript
programs.
Forms require special HTML tags as well as special JavaScript
capabilities -- mainly, special pieces of code called event
handlers. Let's explore the HTML aspects of forms first. You have
to understand them before the JavaScript mechanisms make sense.
- Building Forms in HTML-
HTML has had the power to handle forms for years. Almost since
its inception, HTML programmers have been able to include text
fields, buttons, check boxes, and radio buttons in their Web pages.
Until JavaScript, though, the only thing you could do with a form
was take its contents and send them to a server-side program that
processed those contents and returned some result.
JavaScript enables you to design forms that operate entirely on the
client side. That is, they require no interaction with the server
at all. But the HTML for creating forms remains largely the same.
The lessons in this section teach you how to build HTML forms. The
forms won't do anything (we'll talk about that next), but you'll
get a solid start in making forms look the way you want. HTML
supports several kinds of form elements. These are:
-Buttons: You can have a button that sends information to a server,
a button that returns all elements in its form to their original
states and, most useful to JavaScript programmers, a button that
does whatever you tell it to do.
-Text Handlers: You can create text fields (text boxes of only one
line) and text areas (multi-line text boxes).
-Check Boxes and Radio Buttons: HTML enables you to create check
boxes that surfers can select or deselect, and radio buttons that
exist in groups; only one radio button can be selected at a time.
-Selection Lists: You can create lists of options in which either
all the options are always displayed (like a list box), or only one
option is displayed until the surfer clicks to display the list.
You can set up selection lists so that just one item or multiple
items can be selected.
Next Week: The Syntax for Creating the Three Kinds of Buttons.
Check Boxes and Radio Buttons
by David Wall
Choices, choices. When interacting with a computer program, users
often
need to choose from among several options. Sometimes they're limited
to
one choice, other times, they can choose all, some, or none of the
available options.
JavaScript, like most graphically-aware computer languages,
supports two
option-selection schemes: Check boxes and radio buttons. Check boxes
can
exist on their own, and represent on/off, yes/no conditions. You can
select any, all, or none of the check boxes in a group. Radio buttons,
in contrast, run in packs. You can select only one radio button in a
group at a time. They come in handy for letting the user select
mutually
exclusive options, such as color -- the product the user is ordering
can't be both red and green.
Here's what a check box looks like, generically speaking:
Text displayed next to the check box.
You're familiar with the TYPE and NAME attributes, but VALUE and
CHECKED
are special here. CHECKED, if present, means that the check box is
checked (it contains an X or other mark) when the form is loaded or
reset.
It's also important to understand the difference between the value
of
the VALUE attribute and the text that appears next to the check box --
they're not the same thing. The VALUE attribute may be accessed
through
JavaScript; the text may not. The VALUE attribute and the text may be
the same, but need not be. The text next to the check box need not
exist
at all (you wouldn't want text if you were putting check boxes next to
graphical icons, for example).
The generic code for radio buttons looks the same, but all the
radio
buttons in a given group (a group is a set of radio buttons in which
only one can be selected at a time) have the same value for their
NAME attribute, like this:
Text
displayed next to the radio button.
Text
displayed next to the radio button.
That's the only syntactical difference: Radio buttons must come in
groups of at least two, they are of type RADIO, and all the radio
buttons in a given group have the same name.
Next Week: See Check Boxes and Radio Buttons in Action
THIS WEEK: Forms
by David Wall
We've been talking about the HTML form elements that provide
JavaScript
with a means of taking input and displaying output. Specifically,
buttons have been our recent concern. Here is a complete button demo
you
can load into a browser. The buttons don't do anything yet, other than
render properly.
Several unusual lines of HTML code appear in this script. The first
new
line tells the HTML parser and the JavaScript interpreter that it's
dealing with a form. That line looks like this:
<FORM NAME="Buttons">
The NAME="Buttons" attribute tells all concerned that the form has
a
name -Buttons. The form name will come in handy when JavaScript starts
referring to the contents of the form.
Further down in the HTML, after some other unusual statements, you
see
the line
</FORM>
That's an HTML closing tag; it tells the HTML and JavaScript
interpreters that what's between the opening and closing FORM tags is
part of the form named Buttons.
Between the FORM tags are three unusual lines of code. Each creates
a
different kind of button. The first line,
<INPUT TYPE=SUBMIT NAME="SubmitButton" VALUE="Click Here to Send">
creates a SUBMIT button that, when clicked, sends the contents of
the
form to a server-side program for processing. The VALUE attribute is
set
equal to the string that's displayed on the face of the button. In
this
case, Click Here to Send is what's displayed.
The HTML INPUT tag is used to define all form elements except text
areas. The TYPE attribute's setting determines what kind of form
element
gets displayed.
resets all form components (or would reset them, if there were any
to do
this) to their original states -- again, their original states might
not
be blank.
is the one you need to pay close attention to as a JavaScript
programmer. Buttons of the BUTTON type don't do anything by default --
you have to assign functions to them. You'll soon see how to do this
using a JavaScript facility called an event handler.
None of the buttons in this exercise do anything. The SUBMIT button
has
nothing to submit and nowhere to submit to, the RESET button has no
elements to reset, and the BUTTON button hasn't been linked to
JavaScript code that would give it life. All the buttons will depress
when you click them, but they won't do anything until you learn how to
make them do things.
Next Week: Text Handlers (Text Fields and Text Areas)
Accessing Forms by Name
by David Wall
The point of learning how to create forms in HTML is to enable
surfers
to enter information into those forms and then have JavaScript look at
that information and do something with it. Now, I'll show you how to
refer to the contents of form elements. The form elements won't quite
be
interactive, but you'll be one step closer to making that possible.
There are two ways to refer to the contents of form elements: by
name
and by array position. Both ways require that you delve further into
JavaScript's object-oriented nature. Today, we'll cover access by
name.
Forms have names and so do the elements that make up forms. One way
to
access the piece of information contained in a form element (a text
field, in this exercise) is to refer to it by name. The name of a form
element is the value of its NAME attribute, along with the name of its
form and the document in which that form appears. A reference to a
text
field would look like this:
document.formName.elementName
For now, all documents will be called simply document. Later, I'll
show
you how to distingush between documents in different frames or
different
windows.
The reference above refers only to the element, which is a
container for
a value. The value is usually what interests us. For most form
elements,
the value is referred to like this:
document.formName.elementName.value
That is, the name of the form element followed by the word value,
which
is a reference to the value property of the form element. A JavaScript
reference book (such as David Flanagan's JavaScript: The Definitive
Guide, ISBN 1565923928) or the electronic guide on the Netscape site
at
http://developer.netscape.com/docs/manuals/js/client/jsguide/index.htm
will provide lists of properties -- I'll explore them further soon.
Next Week: An Illustration of What We Learned Today
Enliven Your Forms
by David Wall
We're almost finished exploring form elements. Once I've covered
all of
them, I'll talk about the two ways in which you can refer to form
elements from within JavaScript code (you knew those NAME attributes
were there for a reason).
- Using Selection Lists -
Life is full of choices, but frequently there isn't an infinite array
of
them. Often, you must choose from among a discreet set of options.
HTML and JavaScript support selection lists. The purpose of
selection
lists is to show a group of options and allow the user to choose one
or
more of them. This exercise shows you how to create two different
kinds
of selection lists in HTML documents.
<SELECT NAME="uniqueIdentifier" SIZE=visibleEntries>
<OPTION VALUE="accessibleValue">Visible text
</SELECT>
Really, selection lists comprise two elements -- SELECT elements
and
OPTION elements. The opening and closing tags of the SELECT element
contain multiple OPTION elements, which are the entries in the
selection
list.
The SELECT element takes a NAME attribute, which you've seen
before, and
a SIZE attribute, which dictates how many entries in the selection
list
are visible normally. If the SIZE value is smaller than the number of
options, the list box gets scroll bars to enable you to scroll through
the options. If SIZE is set to 1, the box becomes a drop-down box,
which
you must click to display the list of options.
By putting the attribute MULTIPLE in the opening SELECT tag, you
can
make it possible for the user to highlight multiple entries in the
selection list.
The OPTION element has only a VALUE attribute, which is a value
that's
accessible through JavaScript code. I'll use the VALUE attribute when
I
show you how to find which element (or elements) in a selection list
is
(or are) highlighted.
This shows how it all works:
<HTML>
<HEAD>
<TITLE>Chez JavaScript</TITLE>
</HEAD>
<BODY>
<H1>Menu</H1>
<P>Welcome to Chez JavaScript! What would you like?
<FORM NAME="SelectLists">
<H2>Choose one entree.</H2>
<SELECT NAME="SelectAnEntree" SIZE=1>
<OPTION VALUE="Hamburger" SELECTED>Hamburger
<OPTION VALUE="HotDog">Hot Dog
<OPTION VALUE="FishPatty">Fish Patty
<OPTION VALUE="KiddieMeal">Kiddie Meal
</SELECT>
<H2>Choose as many desserts as you like.
<SELECT NAME="SelectADessert" SIZE=3 MULTIPLE>
<OPTION VALUE="IceCream">Ice Cream
<OPTION VALUE="Donuts" SELECTED>Donuts
<OPTION VALUE="Cookies">Cookies
<OPTION VALUE="Apples">Apples
</SELECT>
</FORM>
</BODY>
</HTML>
Next Week: Accessing Forms by Name
And, Action!
by David Wall
Let's take a look at radio buttons and check boxes in action,
together.
Here's an HTML page that includes both:
This HTML document sets up a group of radio buttons -- in the game
"20
Questions," the mystery object can be an animal OR a vegetable OR a
mineral, but no more than one of those things. Then, it sets up a
group
of check boxes for selecting a truck's options--it's absolutely okay
for
a truck to have both four-wheel drive and a rhino package.
The code for creating a radio button looks like this:
The NAME attribute is important -- it identifies the group to which
the
radio button belongs. See how all the radio buttons defined in this
HTML
document have the same value for their NAME attributes? That means
that
only one radio button with the RadioBunch name can be selected at a
time.
The VALUE attribute comes into play when a JavaScript or CGI
program
wants to determine which of the radio buttons in a group is selected
The
word Animal outside the tag's brackets is just plain text -- it's the
label that appears next to the radio button.
See how one of the radio button tags contains the extra attribute
CHECKED? That's the radio button that's checked by default. You don't
have to designate one of the radio buttons as CHECKED, but you should
because it looks good.
Check boxes are created in almost the same way, except that the
NAME
attribute is unique. Here's a typical one from this exercise: