JavaScript is a programming language that lives inside your Web pages, and lets you control nearly every aspect of the pages.
| JavaScript | Java |
|---|---|
| Cannot live outside a Web page | Can build stand-alone applications or live in a Web page as an applet. |
| Doesn’t need a compiler | Requires a compiler |
| Knows all about your page | Applets are dimly aware of your Web page. |
| Untyped | Strongly typed |
| Somewhat object-oriented | Object-oriented |
So, if they aren’t the same, why do they share a name? Marketing. JavaScript was originally called LiveScript (which, in my opinion, would have been a great name: a scripting language that makes your pages come alive). Unfortunately, in 1995, when LiveScript was developed, Java was quite the buzzword, so the marketing folks decided to name it JavaScript, causing immense confusion ever since.
All the Web pages that we build for this course will be written in XHTML. This is just plain old HTML, written according to the rulebook of XML. Here are the rules. If we write our Web pages according to these rules and the rules of HTML, they will be valid; this will become important later. Most of the time, we will use HTML and XHTML interchangeably; we’ll refer to that as (X)HTML. When we talk about something that is purely XHTML or purely HTML, we will use those specific abbreviations.
You put JavaScript into your pages between an opening
<script> and </script>
tag. To make our pages valid, we cannot use the
tags as shown in the book:
<SCRIPT LANGUAGE="JavaScript"> </SCRIPT>
Instead, we must use lowercase tag and attribute names, and change them as follows. Don’t worry; it will continue to work on old browsers.
<script type="text/javascript"> </script>
Once you enter the content of the <script>,
you are no longer in the world of (X)HTML; you are in the world of
JavaScript. The problem is that a validator doesn’t know this;
all it sees is one big (X)HTML
document, and the < and & characters
are still “special.” In order to tell a validator not to
treat them as special, we do this:
<script type="text/javascript"> // <![CDATA[ // Your JavaScript goes here // ]]> </script>
Lines inside a script that begin with // are JavaScript
comments, which JavaScript ignores. The
<![CDATA[ marks the beginning of a section of
your document where (X)HTML validators treat less than signs
and ampersands as ordinary characters. The
]]> marks the end of the section; after that,
less than and ampersand are special again. Conveniently,
this is just in time
for the closing </script> tag.
Some JavaScript books talk about “protecting a script” this way:
<script type="text/javascript"> <!-- // Your JavaScript goes here // --> </script>
This does not protect less than symbols and ampersands
from a validator; this protects really old browsers (or browsers
that cannot handle JavaScript at all) from displaying the content of
the <script> element as though it were text.
This was important when people were making the transition from
the non-JavaScript-capable Netscape 1.0 to the newer Netscape 2.0.
Since the number of people still using Netscape 1.0 is a fraction of a
fraction of a percent of the Web-using universe, we have decided to
abandon this sort of protection. Instead, since valid Web
pages are far more important, we prefer to protect the
scripts from misinterpretation by validators.
Let’s actually put something into a script, and insert it into a Web page to see how it works.
<script type="text/javascript">
// <![CDATA[
alert("This is JavaScript.");
// ]]>
</script>The word alert is a built-in JavaScript
function which takes one argument.
alert( ) produces a dialog box with the
argument as its message.
Notice that the statement ends with a semicolon. Unlike other languages, the semicolon is not required as long as the statement is the only one on a line. If you put more than one statement on a line, you must use a semicolon to separate the statements. Here’s a “gotcha”—if you want to break a long statement across two lines, make sure you break it at a point where the first line is not a complete JavaScript statement. Otherwise, JavaScript will presume you have two different statements. In the interest of consistency, all of our examples will have semicolons at the end of each statement.
As the book mentions, JavaScript is executed as soon as it is
encountered in the page. If you put the preceding script into
the following page at the two places that are marked, you will
see this effect. If the script is in the <head>
you’ll see the dialog box before the text appears on the page.
[This is really lousy user interface, by the way.]
If it’s in the <body>, you’ll see it
after the first paragraph appears and before the second one appears.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>CIT041J Spring 2003</title> <!-- put the script here first --> </head> <body> <p>Paragraph one</p> <!-- put the script here for the second test --> <p>Paragraph two</p> </body> </html>
The argument to the alert( ) function is a string.
Strings are one of the built-in data types in JavaScript.
Numbers may be integers (without a decimal point) or floating
point (with a decimal point). You have all the standard numeric
operations that you would find in the C and C++ programming
languages: +, -, *,
/, and %. The precedence is the
same as you have learned. Parentheses are evaluated first;
followed by multiplication, division, and mod; followed
by addition and subtraction.
JavaScript gives you as much precision as possible; dividing
two integers will give a floating point result. Thus,
12/4 comes out to 2.4, not
2 as it would in C or C++.
JavaScript also provides the ++ and --
autoincrement and autodecrement operators, which work exactly as
they do in C and C++. A quick review:
|
|
The +, -, *, /, and % operators have a shorthand form:
| This | is the same as this |
|---|---|
x = x + 3; |
x += 3; |
y = y - 5; |
y -= 5; |
m = m * n; |
m *= n; |
z = z / (3 + a); |
z /= (3 + a); |
h = h % 12; |
h %= 12; |
Hey! We just used some variables there, without even declaring them. Technically, that’s OK. As soon as you mention a variable in JavaScript, it springs into existence as a global variable, which is available to all functions in the document. In terms of good programming practice, this is not OK. Always declare your variables before you use them. The variables used in the preceding example about shortcuts could have been declared as:
var x; var y; var m, n, z; // you can declare several at once var h = 3; // you can declare and assign at one go
JavaScript variable names are case-sensitive!
This means that quantity,
Quantity, QUANTITY, and
QuAnTiTy are all different variables! Variable
names must begin with a letter, and must be followed only by
letters, digits, and underscores. Variable names are limited to 255
characters in length. If you get anywhere near this limit, seek
counseling at once. If you have a variable name that consists of
two or more words (such as quantityPurchased), it is
conventional to capitalize the first letter of every word
except the first one. [This style is known as
intercaps style.]
JavaScript is untyped. That means
that you don’t have to say, “this variable can only
contain integers; this one contains only floating point, and that
one over there contains only characters”—any variable can
hold any type of data at any time. A var is a generic
holder of information of any data type.
Back to data types...
In addition to numbers (integer and floating point), variables can hold string data. A string is delimited by either single or double quotes:
var str; str = "This is a string."; str = 'So is this one.'; str = "Isn't it great to have both kinds of quotes?"; str = 'For "situations" like this.';
If you need a string that contains both double and single quotes, you use a backslash to “protect” (or escape) the quotes that should be part of the string:
var str; str = "Mrs. O'Hara said \"Hello\" to us.";
Other useful escape sequences are \t for a TAB,
\n for a newline character, and \\ for
a backslash. You may also produce an arbitrary single-byte character
with the sequence \xnn; for example, the
character ó has the hexadecimal code f3;
so the string acción would be written as
"acci\xf3n". You may also include arbitarray Unicode symbols
in the form \unnnn.
Later in the course, we will learn a large number of functions
for manipulation string. There is only one string operator; the
+ (plus sign), which is used to concatentate
strings.
var str; var firstName; str = "door" + "bell"; // same as str = "doorbell"; // a silly example // read value of firstNamne from user information str = "Hello, " + firstName + ".";
The plus sign is the only operator that is designed to work with both strings and numbers. When you “add” a string and a number, the number gets promoted to a string, and the strings are concatenated. With all other arithmetic operations, the string is converted to a number:
| Expression | Evaluates to |
|---|---|
3 + 4 | 7 |
"3" + "4" | "34" |
3 + "4" | "34" |
"12" / 6 | 2 |
"12" - "6" | 6 |
Whenever you read user input (such as from a form or a dialog box) it comes in as a string. If you are going to use the input in a numeric context, you must convert that string to a number, or else the “addition effect” may give you unexpected results.
Boolean data has two values; true and false.
These values are usually the result of some boolean operation such as
less-than, equal-to, etc. Any value that works out to zero, the
null string, or the null value is considered false;
everything else is true. You’ll mostly use these
values in conjunction with if and while,
statemenets.
See the book, pages 55 through 64. The important points to note are that array indices start at zero, not one. Also, arrays expand as they are used. In the following code, elements with indices 5 through 9 will have the null value.
var data = new Array( "a", "b", "c", "d", "e"); data[10] = "x";
See chapter 3 of the book. The book says that when you have
an if, for, or while
followed by exactly one statement, you don’t need to use
curly braces. We strongly recommend that you put in
curly braces no matter what. First, your code is more consistent.
Second, even if you have only one statement in the action part
of the if or loop, you’d have to put in the
curly braces if you ever added to that code. You may as well do
it sooner than later.