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.
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.
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.
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.
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:
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.
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
Here is a collection of links to articles that do discuss prototype-based inheritance:
Some facts about JavaScript objects:
Object
—all objects in JavaScript inherit from Object
. The base object Object has methods, but no properties.
Two ways of including a JavaScript script in an XHTML document:
directly, through the <script> tag, e.g.
<script type="text/javascript"> // this is a JavaScript script window.document.alert("Hello, World!");
</script>@@@
indirectly, through the use of a <script> tag that specifies an external file, e.g.
<script type="text/javascript" src="helloWorld.js" />
In this case, the file helloWorld.js would be a file on the web server in the same directory as the HTML file that contains the lines of JavaScript code to be executed. A key advantage of putting scripts in external files is that they can be reused on multiple web pages. Often such external JavaScript files contain libraries of functions that can be called in <script> elements that are directly embedded in the page.
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.
A summary of key points from this section:
Number
, String
, and Boolean
.Number
, the properties of the wrapper class are more useful. String
, the methods of the wrapper class are more useful. Number
, and string and String
, so wrapper methods and properties can be used on the primitive objects in most cases. Be sure to look over the diagram on p. 137 that illustrates the difference between primitives and objects in terms of memory management.
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.
Facts to know from this section:
true
or false
null
that is not the same as the number 0, though when used as a boolean, it is treated as false, and when used as a number it is treated as zero. The value null
is used for reference variable that don't refer to any object. null
are subtly different. 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 |
|
String name = "Phill"; |
char 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.
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.
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:
Number
ObjectThis 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
.
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.
The material in this section is pretty much self-explanatory.
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.
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:
typeof
OperatorThe 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));
This section is self-explanatory if you are familiar with assignment statements in C, C++ and/or Java.
Date
ObjectThis 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:
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:
writeln
method is useful only if the browser is used to view a non-XHTML document, which is rarely done." Actually, there is another case where writeln is useful: namely, writing out text inside a <pre>
element. 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.
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.
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").
This section describes the if/else if/else statement, which functions essentially the same as in C/C++/Java. Yawn.
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.
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.
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!)
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:
Array
objects. Among other things, this means
Object
instances in JavaScript applies to Array
objectsArray
objects inherit behavior from Object
.Array
object is more like a Java ArrayList
object—at least prior to Java 1.5, where ArrayList objects can be bound to specific types—in the sense that a pre Java 1.5 ArrayList
is simply an object that implements an array of items of type Object
.Array
object, not a method.
a.length
Array
objects can themselves be Array
objects—this is how multi-dimensional arrays can be implemented. Array
Object Creation From this section, be sure you know
new Array()
syntax.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.
Array
MethodsA 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:
Array
object can be treated as a queue, however the shift()
and unshift()
methods only add and remove from the beginning of a list. A true queue would only remove from the beginning of the list with shift()
, and add to the end. What Array
method would you use to add one element to the end of a list (implemented as an Array
object?) Function definitions are actually quite different from those in C, C++ and JavaScript.
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.)
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:
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
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.
Things to get from this section:
arguments
, with a property arguments.length
(See the example on p. 168).sort
Method, RevisitedIf 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.
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.
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.
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.
String
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.
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.
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.
@@@
@@@