CISC474, Reading Notes for Sebesta,
Programming The World Wide Web, 3rd Edition

Reading notes by Phill Conrad, Asst. Professor, CIS Dept. University of Delaware


Chapter 4: The Basics of JavaScript

This chapter, along with Chapter 5 and Chapter 6, introduces JavaScript. JavaScript is primarily used for client-side scripting—web page features that are computed on the desktop.

The JavaScript interpreter is typically integrated into the web browser itself (e.g. Internet Explorer or Firefox). Some typical uses of JavaScript include:

One point to make about JavaScript right away is that JavaScript has nothing to do with Java. The fact that they share four letters of the alphabet is more about marketing than about technology.

Although the syntax of JavaScript control structures resembles that of Java, C and C++, it is a very different language from Java—chiefly because it uses dynamic typing rather than static typing. In this respect, it has more in common with language such as Perl and Scheme.

4.1 Overview of JavaScript

4.1.1 Origins

A few things you should know from this section:

A few things from this section that are nice to know, but not as crucial (i.e. I wouldn't ask about them on an exam)

A useful web site mentioned in this section: www.ecma.ch, has moved to www.ecma-international.org.

The most relevant section for JavaScript is the set of standards for ECMAScript. Of those, the ECMA-262 specification is most important—it is the standard for JavaScript that all the browsers try to support. It is available as a PDF file.

4.1.2 JavaScript and Java

Two questions about JavaScript vs Java you should be able to answer after reading this section:

Sebesta indicates that "JavaScript does not support the object-oriented software development paradigm" (p. 131). In fact, authors differ on what they say about JavaScript, regarding Object-Oriented Programming.

Some authors say that JavaScript is "object-oriented", while others (including Sebesta) say that JavaScript is not "object-oriented", but rather is "object-based" (see Section 4.2, especially the intro to the section and the footnote on p. 133—apparently, without support for polymorphism, you aren't fully OOP these days. ).

We'll leave such fine distinctions aside, and just note that some concepts of OOP are present in JavaScript (properties, methods, inheritance), but that you may find some limitations for support of the OOP-methodology.

4.1.3 Uses of JavaScript

Three things that server-side languages support that client side JavaScript does not support:

This section notes that JavaScript is an alternative to Java applets.

This section talks about the ways that JavaScript can interact with the XHTML and CSS elements on a page. This is another key advantage of JavaScript over Java Applets—by contrast, Java Applets run in a "window" inside a web page, and cannot directly interact with other elements on the page. In a sense, Java applet is kind of a "self-contained little world", separate from the web page that contains it.

4.1.4 Event-Driven Computation

Although this section is titled "Event-Driven Computation", it is really more about the use of JavaScript for validation of forms. Event-driven computation is covered in detail in Chapter 5.

Some questions you should be able to answer after reading this section:

4.1.5 Browsers and XHTML/JavaScript Documents

This section mainly notes that scripts can appear in either the <head> or the <body> elements of an XHTML document. More detail on this will be presented later in the chapter, so I would suggest not getting too hung up on the detail here.

4.2 Object Orientation and JavaScript

In the intro to this section, Sebesta notes one reason that he (and others) claim that JavaScript is object-based rather than object-oriented: namely, the lack of classes and class based-inheritance in JavaScript. This leads to a lack of support for dynamic binding and polymorphism (see the footnote).

Rather than class-based inheritance, JavaScript has a feature called prototype-based inheritance, which is not discussed in Sebesta. (See links below for more info about prototype-based inheritance).

In spite of all that, you'll see that you really do need a lot of OO-speak to navigate your way through JavaScript

All about prototype-based inheritance

Here is a collection of links to articles that do discuss prototype-based inheritance:

4.2.1 JavaScript Objects

Some facts about JavaScript objects:

 

4.3 General Syntactic Characteristics

Two ways of including a JavaScript script in an XHTML document:

Other aspects of JavaScript described in this section that you should familiarize yourself with:

A particularly problematic aspect of JavaScript is its treatment of semicolons, which is signficiantly different from that of C, C++ and Java. Be sure you read about this on p. 136 in this section.

4.4 Primitives, Operations, and Expressions

4.4.1 Primitive Types

A summary of key points from this section:

Be sure to look over the diagram on p. 137 that illustrates the difference between primitives and objects in terms of memory management.

4.4.2 Numeric and String Literals

For the most part, these work the same way that they do in C, C++ and Java, but be sure to read through the section, because there are a few differences. Here are some highlights:

One thing Sebesta does not mention, but that I've gleaned from other sources: avoid the 0 prefix for "octal" integer values, because it is not interpreted uniformly as octal across different browsers.

4.4.3 Other Primitive Types

Facts to know from this section:

4.4.4 Declaring Variables

The keyword var is used to declare variables. Variables are given a type by assigning them a value of that type, not by preceeding them with a type. Compare the following: note that in each case, the type in JavaScript is assigned implicitly, not explicitly.

JavaScript Java C C++
var x = 1; int x = 1; int x = 1; int x = 1;
var y = 1.5; double y = 1.5; double y = 1.5 double y = 1.5

var name = "Phill";
or
var name = 'Phill';

String name = "Phill"; char name[] = "Phill";

char name[] = "Phill";
or
string name = "Phill";

var found = true; boolean found = true; int found = 1; bool found = true;

Note that declaring variables is optional in JavaScript; you can just use a variable without declaring it first. This can be a real pain, because it means that variables that are misspelled do not produce syntax errors, but instead just make your script behave in unexpected ways.

Sebesta recommends that all variables be explicitly declared, but doesn't mention (at least not in this section) the main reason for doing so. It has do with scope.

Thus, the use of var to declare variable is important to indicate whether you intend a variable to be global or local.

As usual, it is best to keep the use of global variables to a minimum.

4.4.5 Numeric Operators

For the most part, the operators are exactly the ones you are used to from C, C++ and Java, with one exception: although the % operator does do mod (remainder after integer division) the / operator does not do integer division even when both numerator and demoninator are integers. In fact, JavaScript has no separate integer data type—all calculations are done as double precision floating point calculations.

4.4.6 The Math Object

The Math Object in JavaScript includes methods to do the things that would be done with:

This includes things like sin, cos, floor, round, etc.

A reference to these can be found at:

4.4.7 The Number Object

This section describes some useful properties of the Number object for the maximum and minimum values, and special value that represent positive and negative infinity, and the value NaN (not a number).

Note that you cannot use the equality operator to test for NaN—instead, use the predefined function isNan(x), which returns true or false depending on whether x has the value NaN.

4.4.8 The String Catenation Operator

This section notes that + is used for string concatentation (or "catenation" as Sebesta calls it). JavaScript will coerce integers to strings, so you can show the value of a variable x in an alert box with the following code:

var x = 3; 
alert("x = " + x); 

You can see this illustrated on the page ch04/Section4.4.8.example.html

One special thing to note about string concatenation is that + is overloaded for both addition and string concatenation. This, combined with the coercion of types, can to some surprising results if you aren't careful about parentheses.

See the page ch04/Section4.4.8.example.html for an example of where things can go awry if you aren't careful in your use of the string concatenation operator.

4.4.9 Implicit Type Conversions

The material in this section is pretty much self-explanatory.

4.4.10 Explicit Type Conversions

In this section, Sebesta explains the toString() method of the Number object which can be used to convert numbers to the string equivalent in decimal, binary, octal or hexadecimal.

As an example of this in action, see the script ch04/Section4.4.10.example.html, which uses the toString method to convert to binary, octal, decimal or hexidecimal.

Sebesta also claims that the parseInt() and parseFloat() predefined functions are "not often needed". I've actually found them to be needed rather often, in the context of converting numeric data that comes in from XHTML forms; such data always comes in as String data and often needs to be converted to work properly with the + operator, for example.

4.4.11 String Properties and Methods

The String object illustrates that in JavaScript, a lot of thing that would be methods in other languages are actually properties that are directly accessed in JavaScript. For example, length is treated as a property in JavaScript, while in Java, it is a method of the class String:

JavaScript Java
	var firstName="Phill";
 // notice absence of () on next line
 // indicating accessing a property
	var howLong = firstName.length;
	String firstName = "Phill";
	// notice () after length, i
  // indicating a method call
	int howLong = firstName.length();
	

Sebesta also describes various methods of the String object also has various methods including charAt(), indexOf(), substring(), toLowerCase() and toUpperCase(). More can be found at the link below:

4.4.12 The typeof Operator

The typeof operator can be used to check for the type of primitive objects; for these, it returns a string "number", "string", "boolean". However, for all objects or null references, it returns "object". As Sebesta indicates, this illustrates that object references don't really have types in JavaScript—in some sense, all "objects" are of the same type.

This "lack of type" for objects other than primtive objects is one of the major "conceptual" differences you need to wrap your mind around if you are used to the way things work in C++ and Java—I speculate that it may be at the root of why some folks claim that JavaScript is not "Truly Object-Oriented."

The other possibility for the return value of the typeof operator is "undefined".

A sample question to test your understanding of Section 4.4.12. The following always returns the same value, regardless of the context in which it appears. What is that value?

typeof(typeof(x)); 

4.4.13 Assignment Statements

This section is self-explanatory if you are familiar with assignment statements in C, C++ and/or Java.

4.4.14 The Date Object

This section is mostly self-explanatory, except for one suspected typo:

This brings up one "pitfall" in working with Date objects in JavaScript that it would have been good for Sebesta to point out: namely, that months start numbering from zero, not one. Thus, to produce a Date object for the US Holiday known as Independence Day (July 4th), it is necessary to use

var indepDay = new Date(2006,6,4); // July 4th, 2006

NOT

var notIndepDay = new Date(2006,7,4); // actually August 4th, 2006

You can verify this with a trick that works in both Internet Explorer and Firefox, and probably with other web browsers that support JavaScript as well—namely, you can put JavaScript code into the URL box in a web browser, preceeded by the text "javascript:", and it will show the result of the expression as a web page. For example, type either of the following to your web browser (or just click on the hyperlinks below) and notice what output you get.

javascript: new Date(2006,6,4);

javascript: new Date(2006,7,4);

More information on the Date methods can be found at:

4.5 Screen Output and Keyboard Input

This is one of the most useful sections in the entire chapter; it marks a turning point from sort of "theoretical background" about JavaScript and "reference manual" type stuff towards "practical advice on getting things done", including a complete JavaScript example script.

So, I'd advise you to read this section from beginning to end carefully.

A couple of quibbles about things that Sebesta mentions in this section:

CS textbook JavaScript vs. Real World JavaScript

The script shown in this section is typical of those written by beginning JavaScript programmers—especially those that come from a Computer Science background or programming background, rather than from a web designer background. It uses JavaScript in the same way that C, C++ or Java are used—to prompt a user for values, and then print out those values in a kind of linear fashion. However, this is a rather unrealistic scenario for using JavaScript.

Instead, most real world uses of JavaScript are event based. In real world JavaScript, the following is more typical.

DHTML is not a separate technology from JavaScript. Rather, DHTML is a particular way of using JavaScript together with something called the Document Object Model,or DOM for short.

The DOM provides methods and properties that correspond to the elements and attributes of an XHTML document, and the CSS properties and styles that can be applied to that document. JavaScript code can be used to pull values out of fields in a form, compute something, and then change the content or style of web page elements.

Fortunately, these techniques are covered in Chapter 5 and Chapter 6 of Sebesta. My point in bringing it up here is just to let you know that

One more thing, on the positive side—while the techniques illustrated in the script from Section 4.5 such as alert(), confirm(), and prompt() are used sparingly in production JavaScript, they are very useful in the development and debugging phase. So it is still worthwhile to dig into the example script on page 149, and the material in Section 4.5 before moving on.

4.6 Control Statements

Most of what is in this section is unsurprising and familiar to those who known C, C++ and/or Java, however there are a few gotchas!

In the reading notes, l'll highlight the parts that you need to pay special attention to—those places that are different from what you'd normally expect.

The first appears in the intro to the section on p. 150—note what Sebesta says about variables declared inside a compound statement (i.e. inside a set of { } braces.) Unlike C, C++ and Java, these variables are not local to the block. In fact, JavaScript does not have "block scope" at all. In JavaScript, variables are either local to an entire function, or they are global—period.

4.6.1 Control Expresssions

This section decribes the relational operators. Note that one difference is the appearence of the === and !== operators, which are different from == and != operators. Be sure you understand the difference (explained on p. 150).

Also surprising is what happens with use a Boolean object (as opposed to a primitive boolean value) in a conditional expression. I'll offer some course credit for the first one or two examples of good web pages illustrating this point (provided I'm given permission to archive those pages for future CISC474 classes, and edit and adapt them, with credit to the original authors.) Email me with subject line ("CISC474: Sebesta Section 4.6.1").

4.6.2 Selection Statements

This section describes the if/else if/else statement, which functions essentially the same as in C/C++/Java. Yawn.

4.6.3 The switch Statement

The switch statement is a bit different though, in the sense that case labels can be of different types. That is not true in C, C++ and Java.

This section also includes an example document—interesting because of the discussion of how this document would interact with a validator.

4.6.4 Loop Statements

For the most part, this section contains unsurprising material about the for, while, and do-while loops, which function the same as their C/C++/Java counterparts. Only the for-in loop is different, and that isn't explained until Section 4.7.

4.7 Object Creation and Modification

I highly recommend a detailed read of this particular section! Among the interesting things in this section are

This section also illustrates the two ways that property values can be accessed—be sure you are clear on this point:

The two notations are equivalent, but are useful in different contexts. Note that the second can be used with a variable, as in:

var whichProperty = window.prompt("What property do you want?","");
var requestedProperty = my_car(whichProperty);

The example above illustrates the power of JavaScript—In a language where properties can only be accessed with fixed variable names or with "getter" methods, you would have to use a series or if/else statements or a switch statement that covered all the possibilities for whichProperty to implement equivalent code. In some ways, this aspect of JavaScript makes it more like LISP or Scheme, in the use of "property lists". (Perhaps, CISC280 now appears more useful than you might have expected!)

4.8 Arrays

Arrays in JavaScript are very different in several ways from arrays in C, C++ and Java. So this section is one that you should read in detail.

Some key things to note that may be different from what you'd expect:

4.8.1 Array Object Creation

From this section, be sure you know

4.8.2 Characteristics of Array Objects

This section provides some example code for working with JavaScript arrays. The example code illustrates that apart from the use of .length as a property rather than as a method, most of the conventional operations on arrays work as you'd expect.

4.8.3 Array Methods

A variety of useful methods are presented here, including join(), sort(), concat(), slice(), and toString().

While you don't need to memorize these, it is good to read through this section so that as and when you need these methods, you'll know where to look for them.

It is also useful to know that there are built in methods for treating an array as a stack known as pop(), push().

Here's an exercise to test your understanding and careful reading of this section:

4.9 Functions

Function definitions are actually quite different from those in C, C++ and JavaScript.

No fixed return type or types for parameters

The main difference is that when defining functions in JavaScript, you don't declare the return type or the types of the parameters; those are all determined dynamically at run time. Thus, a function can accept and return different types of data depending on the context.

In practice, sometimes this is what you want, and sometimes it isn't. It can be useful to document data types you are expecting to receive and return in comments before your functions. It can also sometimes be useful to use the typeof operator to check the types of the parameters you pass in to make sure they correspond to what you expect.

An annoying thing: the number of parameters is not checked between function definition and function call—a mismatch in the number of parameters will not produce a syntax error! Rather, formal parameters missing from the function call will be set to "undefined", while excess actual parameters will just be ignored. On other other hand, this means that all functions can take a variable number of arguments through a property array arguments, with a property arguments.length (see Section 4.9.3 for details.)

The mind-blowing part: functions are first-class objects

Functions are treated as objects. This aspect of JavaScript make it more like LISP or Scheme than C, C++ or Java.

In fact, there are even lambda functions in JavaScript (anonymous functions passed as data). Lambda functions turn out to be of practical use in some aspects of AJAX programming because of the "asynchronous" nature of AJAX event handlers. There is even an example of a JavaScript lambda function in Sebesta—the anonymous function passed into the sort method in the code example on p. 171.

Fortunately (or unfortunately depending on your point of view) we won't spend much time on that aspect of JavaScript. However, If you are a LISP/Scheme fan or a programming language nerd, and want to dive deeply into this aspect of JavaScript, here's are two neat articles:

4.9.1 Fundamentals

Most of the text in this section is fairly standard stuff—it is the syntax of the example on p. 166 that you should focus on, and the last two paragraphs. This section doesn't yet cover the use of parameters—that appears in Section 4.9.3

4.9.2 Local Variables

There are a few surprising things about how scope works in JavaScript that are described in this section. Read carefully to discover answers to these questions:

One thing Sebesta does NOT mention that is nevertheless important: there is no block scope in JavaScript. This is quite different from what you may be used to in C, C++ and Java. For instance, consider this example:

function makeSquareTable(n)
{
  var i;
  document.writeln("<table>")
  for (i=1; i<=n; i++)
  {
     var iSquared = i * i;
     document.write("<tr>");
	    document.write("<td>" + i + "</td><td>" + iSquared + "</td>");
	    document.writeln("</tr>");
  }
  document.writeln("</table>");
}

A suggestion to Sebesta: I think this is one place where it would be worthwhile to go into some more detail. A few examples would help. Also the issue that there is no block scope in JavaScript should definitely be mentioned, along with an example. There are two reasons for this (1) it is an important issue in JavaScript, and (2) because it is an important issue in Computer Science in general.

4.9.3 Parameters

Things to get from this section:

4.9.4 The sort Method, Revisited

If you need to sort something in JavaScript, this is an important section to read—it explains how to pass in a comparison function to get the sort to work properly. You'll also need to look over this short section to be able to understand the example in Section 4.10.

4.10 An Example

My comments on real world vs. textbook JavaScript from the notes on Section 4.5 apply equally to this example. However, it is still worth reading through to get a feel for some more complex JavaScript code. It helps a lot to be fairly comfortable with a few of the oddities and complexities of JavaScript before you can write effective DHTML or AJAX code.

4.11 Constructors

If you plan to develop your own objects in JavaScript, or want to understand why JavaScript is called an "object-based" language rather than an "object-oriented" language, this section is important reading. Otherwise, you can probably skip over it.

4.12 Pattern Matching Using Regular Expressions

This section is very useful for particular applications in JavaScript—however, I'm going to suggest that you consult it as and when you need it. Just skim over it for now to understand what regular expressions can do for you, and then refer to the details as and when necessary.

Note that regular expression methods and functions are also available in Java, Perl and PHP, as well as editors such as vi and emacs. So mastering the use of regular expressions is a very useful skill.

4.12.1 Character and Character-Class Patterns

4.12.2 Anchors

4.12.3 Pattern Modifiers

4.12.4 Other Pattern-Matching Methods of String

4.13 Another Example

This example is a good one to illustrate very simply the use of JavaScript to validate various kinds of input—separated from all the details of how to get data out of an XHTML form. It also shows how you can test a JavaScript function in the context of a simple web page—a sort of very simple "test-driven development" approach— before plugging it into a larger web page.

4.14 Errors in Scripts

This section contains some very useful advice about configuring your web browser (especially Internet Explorer) to show JavaScript errors.

My experience is that using Firefox when debugging JavaScript is much nicer than using Internet Explorer—the JavaScript console gives much better feedback when things go wrong. However, this is a matter of individual taste—also, I'm told that there are some nice "add-ons" for IE that make JavaScript debugging easier.

This is an opportunity for some course credit—a tutorial and survey on JavaScript debugging tools and techniques. Let me know if you are interested.

4.15 Summary

This is a good summary of things you should have picked up from reading the Chapter on JavaScript and the reading notes. I recommend looking over it. If there is anything that you didn't pick up, then its a good bet that you probably need to review part of the chapter again.

4.16 Review Questions

@@@

4.17 Exercises

@@@


Valid XHTML 1.1 Valid CSS!