Table of Contents
Sample Chapter
Talk About It
Buy It!
Web Refs
About The Author

Book Updates

This is a sample chapter from the book, reproduced exactly as contained therein. If you'd like to learn more about Dynamic HTML, you are invited to explore the Table of Contents or take the plunge and buy the book from Regardless, thanks for reading this and I hope you find it interesting, informative, and entertaining!

Session 3: 30-Minute Crash Course on JavaScript

Session Checklist

  • Variables
  • Expressions and conditionals
  • Looping mechanisms
  • Subroutines, built-in and user-defined

The first wave of Web browser development came in the mid-1990s, as the team at Netscape Corporation released the first version of Netscape Navigator. It offered support for the relatively primitive version of HTML that was available back then. With little more than bullet lists, paragraph breaks, and crude tables (an experimental addition at the time), people were still doing remarkable things and creating valuable Web sites for the online community.

In the second major wave of Web browser development in the late 1990s, the Netscape team recognized that, even with lots of evolution, HTML wasn't going to prove sufficient to meet the needs of designers and developers. A scripting language was a logical addition, and the innovation that Netscape added was JavaScript.

NOTE: A little-known bit of trivia is that the original name for Netscape Corporation was Mosaic Communications, named after the original Mosaic Web browser from the University of Illinois. The regents of UIUC didn't like an independent company naming itself after a UI trademark, so Mosaic Communications became Netscape. You can see a tiny bit of this original name left over: Go to and see where you end up!

Why JavaScript instead of an existing, known language? Because simultaneous to this second wave of browser development, another company, Sun Microsystems, was beginning to promote a platform-neutral programming language that it called Java. The Java programming language gave developers the capability to write software applications that simultaneously works on Macs, PCs, Unix boxes, and more. Netscape faced just one catch: how to distribute these applications? The solution was to incorporate the Java runtime environment into the Web browser itself, and that was an important addition.

Microsoft didn't like someone else telling it what scripting language to include in its browser, so the early versions of Internet Explorer included support for Visual Basic Script, the company's alternative choice. The problem was that no Web sites used VB Script, while everyone was using JavaScript. Eventually, Microsoft succumbed and the tale ends with JavaScript receiving a universal blessing as the standard and incorporation (albeit, loosely) into the HTML 4.0 specification.

To correct a common point of confusion, JavaScript and Java aren't the same. In fact, Java is what's known as an object-oriented programming language, and it's not for the faint of heart. JavaScript, however, which shares only some minimal syntax structure in common with Java, is a simple scripting language that you can add to your Web pages quickly and easily.

This session gives you a quick overview of the basic structure and format of the JavaScript language. Don't panic, however _ as I said, JavaScript isn't a heavy-duty programming language, and you needn't anticipate something that requires thousands of lines of obscure punctuation marks and hieroglyphics! Quite the opposite, in fact: JavaScript is small, elegant, and very powerful, as you soon see.


The building block of all scripting is variables, the named containers that store specific information and enable you both to manipulate and display it whenever you want. If you remember your algebra, where x=y+4, you're already familiar with variables, because that's what the x and y are in that equation. If you imagine the two variables as boxes that can take on any value, the equation describes a relationship between them. If y is 10, x is 14.

JavaScript features three primary types of variables that you need to know: numeric, string, and Boolean. Numeric variables are just like the x and y of the preceding paragraph and can store either an integer value (123) or a floating-point value (4.4353). String variables store a sequence of letters, digits, or punctuation. By using a string variable, you can say name = "Dave Taylor" and it has the effect of putting the letters D, a, v, and e (and so on) into the container name. By contrast, Booleans can have only one of two possible values: true or false.

Examples of different values

The most complex of the variable types, numeric variable can hold values that are positive or negative and can have a fractional portion or not. Table 3-1 summarizes the different numeric values.

Table 3-1: Acceptable Numeric Values in JavaScript
Value What It Is
123 Positive integer
-14 Negative integer
14.43 Positive floating point value
-0.5 Negative floating point value with fractional part

You express the values of string variables by surrounding them with quotes. Usually, you use the double-quote character, but JavaScript is forgiving, and you can use the single-quote to surround the value, too, if you want. Either of the following two values are acceptable for a string in JavaScript:

"An exploration of inner space" 'test, test, and test again.'

The third type of variable is a Boolean, and it can take on either a positive true or negative false value. You use it for conditional tests and flags (variables that track the status of a sequence of code), as they're known.

NOTE: Booleans are named after George Boole, a famous British logician.

You can embed some special characters in strings by using a backslash notation that's identical to what you use in both C and Java, as shown in Table 3-2.

Table 3-2: Common Backslash Values in JavaScript Strings
Value What It Does
\\ The backslash character
\r A carriage return
\n A line feed
\b A backspace
\t A tab
\' A single quote (as in "It\'s what I want.")
\" A double quote

Defining and assigning variables

To use a variable, you need to define it beforehand, which is easily done by using the var statement. To demonstrate, the following examples show the definition of a couple variables:

var name; var monthly_wage;

One cool thing about variable definitions is that you can actually make an initial value assignment at the same time! You can modify the preceding examples as follows:

var name = "Sean Connery"; var monthly_wage = 3500;

Notice something else on all these lines: They all end with a semicolon. Every statement in JavaScript must end in a semicolon.

TIP: I keep saying that you must define every variable by using a var statement, but that's entirely not true. JavaScript is a loosely typed programming language, so you can implicitly define variables simply by using them in your script. I highly recommend, however, that you define them.

After you define variables, of course, you want to assign values to them. This procedure, too, is easy, as the following example shows:

var x, y = 3; x = y + 4;

This example results in the variable x containing the value 7 and the variable y containing the value 3.

Expressions and Conditionals

Much more interesting than assignment statements are expressions, which are the real building blocks of JavaScript. Expressions can evaluate to a Boolean (as in "if this condition is true, then . . .") or can evaluate to a string or numeric expression. Table 3-3 takes a look at each of these expressions.

Table 3-3: Three types of expressions in JavaScript
Expression What It Evaluates To
x + y > z Evaluates to a Boolean: either true or false.
x+(2*y)-3 Evaluates to a numeric value, the sum of these two variables.
name + " (given name)" Appends the specified string to the end of the value of the string name.

To understand how each of the expressions work in Table 3-3, I need to assign values to the variables in question. Here's how they may look:

var x, y, z, name; x = 20; y = -5; z = 4.5; name = "Ashley Taylor";

The first expression shown in Table 3-3 is evaluating whether x + y is greater than z. x = 20 and y = -5, so x + y = 15. z = 4.5, so yes, x + y is greater than z. An interesting thing to notice here is that JavaScript can implicitly coerce numeric variables from one type of number to another, so it can compare the integer value 15 to the floating-point value 4.5 correctly.

In the second expression, you're back to algebra. (Just when you though you were safe!) Because x = 20 and y = -5, 20 + (2 * -5) - 3 reduces to 20 + -10 - 3, which ends up as 7. JavaScript uses a standard operator precedence to evaluate mathematical expressions, so it evaluates parenthetical expressions first and does multiplication and division before addition or subtraction.

In the third expression, you get a peek at one of the many powerful string-manipulation features of JavaScript: the + between two string values is the concatenation function. It's similar to the strcat() function in C (if you're familiar with that programming language). What I think is most interesting about the concatenation function in JavaScript is that, because the language is so loosely typed (that is, variables can flip from integer to floating point, to strings and back with minimal effort), you can do things in JavaScript that you definitely can't do in any other programming language, such as is shown in the following example:

oddstring = name + ", and x = " + x;

The numeric value x automatically converts into the equivalent string value before JavaScript concatenates it to the other values. If name is "Ashley Taylor" and x is 20, the resultant value of oddstring is "Ashley Taylor, and x = 20".

You have a ton of helpful shortcuts for expressions, including the common ++ and -- notation from C to increment or decrement a variable, respectively, and += and -= to add the right-hand-side of the expression to the existing value on the left (or subtract). Here's a quick example:

salary = 20; salary++; // now salary is 21 salary--; // salary is back to 20 salary += 10; // salary is 30: this is identical // to salary = salary + 10; salary -= (5+5); // salary is back to 20
TIP: Comments in JavaScript begin with a double-forward-slash and continue to the end of the line.

One area where programming languages diverge is with the notation for equality testing, and JavaScript does its own thing here, too. Unlike Perl, C, or Pascal, for example, JavaScript uses == as an equality test for numeric or string values and != for inequality tests. A few quick examples (and remember that all these evaluate to a Boolean value of true or false) are as follows:

salary = 20; newsalary = 20; name = "Ashley"; newname = "Gareth"; val = (salary == newsalary); // false val = (name == newname); // false val = (name == name); // true val = (name < salary); // false [see note] val = (name != newname); // true val = (salary < newsalary+1); // true

I hope that these examples are straight foward and that you can see how I reach the different values that I cite in the comments. The only weird one here is the middle one: Comparing the string value name with the numeric value salary forces salary to convert to its string equivalent 20 and then compares the two strings. JavaScript considers a string as lesser than another if it appears earlier in a so-called dictionary sort. As a result, 2 (the first character of the string "20") appears earlier in a dictionary than A (the first letter of "Ashley") so the test to determine whether A is less than 2 (in essence) proves false.

NOTE: A sneaky shorthand that many JavaScript programmers use is the comma operator, which enables you to put multiple statements on the same line without using semicolons. By using this notation, you can write the first line of the preceding code listing as salary = 20, newsalary = 20;.

Looping Mechanisms

I know that the information that I present in the preceding (and following) sections is a lot to absorb _ this whirlwind introduction to JavaScript. If you're finding you're starting to get a headache, I recommend that you consider either saying "No worries, mate" and go straight to the next chapter, coming back here as you find JavaScript structures that don't make sense, or taking a few hours off of our crash course to check out JavaScript Weekend Crash Course.

I hope that you're still with me!

Although writing programs without any sort of looping or conditional execution is theoretically possible, doing so is a complete nightmare, requiring you to type and type and type till the cows came home. Instead, JavaScript offers a typical lineup of looping and control structures, as shown in Table 3-4.

Table 3-4: Common JavaScript Looping Mechanisms
Looping Mechanism What It Does
if (expr) statement Conditionally executes statement or statement block.
else statement (If you tie it with the if statement) Executes statement if expr is false.
switch (expr) Acts as a case statement, a series of if/else tests.
while (expr) statement Loops, continually executing statement until expr is false.
do statement while (expr) Same as while, but guarantees one time through loop.
for (expr1;expr2;expr3) statement Loops, continually executing statement until expr2 is false: expr1 is the initializing expression prior to looping, and expr3 is done after each loop but before expr2 evaluates.

Some of these are pretty straightforward. Writing if (a < 10) a = 10;, for example, indicates that you want JavaScript to evaluate the conditional expression a < 10: if it's true, the subsequent statement, a = 10, executes. If the conditional is false, the value of a remains untouched.

A more complex conditional statement may look as follows:

if (name == "Ashley") salary = 20; else if (name == "Gareth") salary = 10; else salary = 15;

In this case, you're testing the value of variable name multiple times. If the value is "Ashley", salary sets to 20. If it's Gareth, salary is 10. And for everyone else, salary is 15.

Switch statements

Another way to write the set of conditional statements that I present in the preceding section is to use the nifty switch statement, which saves typing and looks cleaner, too, as shown in the following example:

switch (name) { case "Ashley": salary = 20; break; case "Gareth": salary = 10; break; default: salary = 15; break; }

Is this sequence easier to understand than the earlier sequence of if/else statements?

TIP: Anywhere that you can place a single statement, you can also place a block of statements by wrapping all of them in curly brackets. You can see that in the preceding example using the switch statement, and you see it appear again shortly in this session.

Notice that you can have dozens of different case values and that they can consist of any constant value _ that is, using anything similar to the following examples is okay:

case 3: case 4+5*3: case "test": case "number" + " ":

They're all constant (unvarying) values, but you can't use variables as case statement expressions, so both the following examples are illegal:

case name: case x + 30:

If you need to use statements similar to the last two, you need to jump back to the if/else structure that I describe in the preceding section.

While loops

The control structures that I describe in the preceding sections enable you to conditionally execute one of a set of statements. The while loop serves a very different purpose, however, in that it enable you to execute the same set of statements multiple times. Here's a typical usage:

var countdown = 10, salary = 10; while (countdown > 0) { salary += salary; countdown--; }

The code starts out by defining two variables. It initializes countdown with a value of 10 and also initializes salary as 10. Then the while loop controls how many times the subsequent block of statements (remember the meaning of the curly brackets?) executes. Within each iteration of the loop, salary adds to itself and then the countdown variable decrements by one. After ten times through this loop, the while condition evaluates to false, and it's done.

NOTE: After the loop finishes, what is the value of salary?

Sometimes you want to have a loop where the statements always evaluate once, even if the condition is immediately false. Using a control structure such as while (expr) doesn't work, because the expression is false and the statements are skipped. You could ostensibly use an iteration counter such as you see in the following example:

var timesthrough = 0; while (timesthrough == 0 && expr) { statements timesthrough++; }

But frankly, what this example shows is pretty awkward. Instead, a more graceful solution is to use the do/while loop instead, as in the following example:

do { statements } while (expr);

Only a slight variation on the tune, the do-while loop is a great control structure to have in your utility kit!

For loops

Don't let the complex appearance of a for loop turn you off; it's the most useful looping mechanism in JavaScript. A for loop consists of three components: an initializer, a conditional, and a loop increment, as you see in the following example:

for (var j = 0; j < 10; j++) { salary += salary; }

The preceding setup is 100 percent identical to the following example:

var j = 0; while (j < 10) { salary += salary; j++; }

The for loop is just a delightfully succinct way to express this sort of sequence.

TIP: Did you notice that the variable definition (var) slipped into the for loop initializer? Neat, eh?

Subroutines, Built-in and User-Defined

Many programs have sequences of statements that appear over and over again. Smart programmers turn those into subroutines, named functions that you can invoke anywhere in your JavaScript. A simple function may look like the following example:

function swap(a, b) { var hold = a; a = b; b = hold; }

This function enables you easily swap the values of any two variables, which you can reference in your JavaScript with swap(name, address);.

Subroutines can also return values by using the return statement. Here's a subroutine that returns the square of the given value:

function square(x) { return (x * x); }

A statement such as y = square(20); results in y having the value of 400 (20 squared).

Built-in functions

The really good news is that hundreds of different functions are built in to the JavaScript language so that most of your user-defined subroutines end up implementing your algorithms instead of doing the real dirty work of string or number manipulation.

Because JavaScript is a roughly object-oriented programming language, you invoke many functions by essentially appending their names to a given variable. As an example, you obtain the length of the string variable name by using the following code:


So you can use this attribute in a conditional as follows:

if (name.length > 50)

Frankly, I find this notation kind of funky and weird. I'm used to a structure that's much more like that of the Perl length(name) function, but JavaScript ain't Perl, and you ain't in Kansas any more!

JavaScript uses way more built-in functions that I can squeeze into this book, but Table 3-5 highlights some that are of particular value to DHTML developers.

Table 3-5: Some Great JavaScript Functions for DHTML Developers
Function What It Does
back() Returns to the previous URL.
close() Closes the specified window.
confirm() Confirms an action with an OK/CANCEL answer.
open() Creates and opens a new window.
submit() Submits the specified form, as if you'd clicked the SUBMIT button.

How can you use these functions? How about as in the following example:

if (confirm("Are you sure that you want to close this window?")) close();

This code causes a dialog box to pop up reading, Are you sure that you want to close this window? along with two buttons: OK and Cancel. If you choose OK the confirm() function returns true and the close() statement executes. (The window closes.) If you choose Cancel, confirm() returns false and it skips the close() statement.


This 30-minute session covers a lot of ground, giving you a quick and easy overview of the JavaScript programming language. JavaScript is a cornerstone of Dynamic HTML, and later in the book, I spend quite a bit of time showing you how to use and exploit JavaScript so that your pages jump through hoops for you.

Starting with an overview of variables, numeric, string, and Boolean, I move to a discussion of how to assign specific values to variables, including a discussion of the JavaScript string concatenation construct. Next is an overview of conditional expressions and the if/else construct, which I follow with a discussion of the two variants of the while loop and the confusing but useful for loop. Finally, I provide a discussion of how to define your own functions in JavaScript and a brief list of some of the most useful JavaScript functions for DHTML developers, wrapping up the chapter.

Quiz Yourself

  1. What fundamental problem forced Microsoft into adding support for JavaScript to Internet Explorer?
  2. Three types of variables are in JavaScript, but one of them can have two different types of values. All things considered, what are the four types of values that you can place in a JavaScript variable?
  3. Which of the following is a correct assignment statement and which is a correct conditional comparison of two numeric values?
    a = 3, a == 3, a := 3; a ?= 3, a.value = 3;
  4. Write a string assignment where you give the variable oddstring a value that contains both a single and double-quoted passage.
  5. What character sequence denotes a comment in JavaScript?
  6. Write the for loop equivalent to the following JavaScript. (This one is a bit tricky!)
    a = 3, b = 5; while (a + b < 10) { do_something(); a += 2; b -= 1; }
    This is a sample chapter from the book, reproduced exactly as contained therein. If you'd like to learn more about Dynamic HTML, you are invited to explore the Table of Contents or take the plunge and buy the book from Regardless, thanks for reading this and I hope you find it interesting, informative, and entertaining!

© 2001-2002 Dave Taylor & HungryMinds, Inc.