A Crash Course in JavaScript
This section will introduce you as quickly as possible to JavaScript. If you're already familiar with the language, you can skip this section for now, though the tables in this section may come in handy later as a kind of quick reference.NOTE
If you have already read Chapter 12, "ColdFusion Scripting", much of this section may seem a bit redundant. However, ColdFusion's scripting language is quite a bit different from JavaScript. In some ways, the two languages can be said to be very similar, particularly with respect to the statements they support, and the way the basic syntax works (curly braces, parentheses, and so on). They are completely different in other ways, such as the operators they support and the way they treat objects.
JavaScript Language Elements
While it's not possible to fully introduce you to the JavaScript language in these pages, it's important for you to at least understand the basic language elements available to you. The next few pages list each of the core JavaScript statements, and can be used as a sort of mini-reference. If you need further information about these items, they will be covered in detail in any JavaScript book or comparable online resource.For clarity, I have broken the statements into four groups:
- Basic statements
- Statements for looping
- Statements for creating functions
- Statements for error handling
The Basic Statements
Table 17.1 lists the basic JavaScript statements. By "basic", I just mean all the statements that aren't specifically for looping, creating functions, or error handling.
STATEMENT | DESCRIPTION |
---|---|
if .. else | Implements simple if / else processing. Comparable to the <cfif> and <cfelse> tags in CFML. |
switch | Executes different blocks of code based on the current value of some variable or expression. Comparable to the <cfswitch> and <cfcase> tags in CFML. |
with | Establishes the default object for evaluating methods and properties. Generally used to make code easier to read and type. Though handy when used correctly, with is not for the faint of heart because it can lead to confusing unexpected behavior. There is no direct equivalent in CFML. |
var | Creates a variable that is local to the current context. Generally, var is used to create variables that are only visible within the body of a function. Comparable to the <cfset var> syntax allowed within CFML <cffunction> blocks. |
Statements for Looping
Like CFML, JavaScript provides a number of different ways to loop over blocks of code. Table 17.2 lists the various types of JavaScript loops, which correspond to various flavors of the <cfloop> tag in CFML.
STATEMENT | DESCRIPTION |
---|---|
for | The simplest and most familiar type of loop. Creates a loop block that advances the value of a counter with each iteration; the loop continues until the value reaches a certain value. Comparable to <cfloop> with from and to attributes in CFML. |
for .. in | Creates a loop block that iterates over each of the values in a given object or array. Comparable to a <cfloop> with collection and item attributes in CFML. |
while | Creates a loop block that executes until a particular condition is no longer true. If the condition is already false when the loop is encountered, it is skipped altogether. Similar to a <cfloop> that uses a condition attribute. |
do .. while | Creates a loop block that executes until a particular condition is no longer true. The loop is guaranteed to execute at least once. There is no direct counterpart in CFML, but it's similar to a <cfloop> that uses a condition attribute. |
break | Breaks out of a loop block. Execution continues on the first line following the loop block. Comparable to <cfbreak> in CFML. |
continue | Skips the remainder of a loop block for the current pass through the loop. There is no direct counterpart in CFML. |
Here's a while loop that does the same thing:
for (i = 0; i < 10; i++) {
...your code here...
}
Another while approach:
i = 0;
while (i < 10) {
...your code here...
i = i + 1;
}
This for .. in loop is functionally equivalent:
i = 0;
while (true) {
...your code here...
i = i + 1;
if (i >= 10) {
break;
}
}
var myArray = [0,1,2,3,4,5,6,7,8,9];
for (i in myArray) {
...your code here...
}
Statements for Creating Functions
Elsewhere in this book, you learn how to create your own functions for use in CFML code (see Chapter 12, "ColdFusion Scripting", for one method, and Chapter 19, "Creating ColdFusion Components", for another). You can also create functions for use in JavaScript code, using the statements listed in Table 17.3.
STATEMENT | DESCRIPTION |
---|---|
function | Creates a function that can be called elsewhere by name; also establishes the function's input arguments, if any. Comparable to the <cffunction> and <cfargument> tags in CFML. |
return | Stops function execution, returning a particular value as the function's output. Comparable to <cfreturn>, though return can be used anywhere within the body of a function, rather than only at the end. |
Here's another function that returns the absolute value (the positive version) of whatever number is passed to it (actually, there is a built-in Math.abs() function that does the same thing; I'm just trying to show as many statements working together as possible):
function multiplyNumbers(num1, num2) {
return num1 * num2;
}
function absoluteValue(number) {
var result;
if (number < 0) {
result = 0 - number;
} else {
result = number;
}
return result;
}
Statements for Error Handling
Table 17.4 lists the statements available for throwing and handling exceptions (errors) within your JavaScript code.
STATEMENT | DESCRIPTION |
---|---|
try .. catch .. finally | Tries to execute a block of code, catching any exceptions. You can respond to the exceptions in the catch block, much like the <cfcatch> tag in CFML. Throws a custom exception (error). Comparable to <cfthrow> in CFML. |
throw | Throws a custom exception (error). Comparable to <cfthrow> in CFML. This is a relatively recent addition to JavaScript and is not available in all browsers. |
<script language="JavaScript" type="text/javascript">
try {
// Comment out the next line to see the error catching behavior
var firstName = "Winona";
alert("I will now try to display the value of the firstName variable.");
alert(firstName);
} catch(e) {
// If any errors occur...
alert("Hmmm, looks like there is no firstName variable. Sorry!");
} finally {
// This portion executes no matter what, error or no error
alert("Well, I hope you enjoyed our little exercise.");
}
</SCRIPT>
JavaScript Operators
Like any other language, JavaScript provides a set of operators for doing things like assigning values to variables or comparing values. Table 17.5 lists most of the JavaScript operators you are likely to encounter; refer to a JavaScript guide for a complete list. If you're familiar with C or Java, these operators will be very familiar to you. If not, that's okay, too.
STATEMENT | DESCRIPTION |
---|---|
= | Variable assignment, like in CFML. |
== | Equality test, like EQ or IS in CFML. |
!= | Inequality test, like NEQ or IS NOT in CFML. |
++ | Increments a value by one, as in i++ (which is a shortcut for i=i+1). |
-- | Decrements a value by one. |
&& | Logical "and" operator, like AND in CFML. Just as in CFML, you can use parentheses to clarify what you want the operator to affect (same goes for the next two operators). |
|| | Logical "or" operator, like OR in CFML. |
! | Logical "not" operator, like NOT in CFML. |
+ | Numeric addition or string concatenation. Be careful not to use & for string concatenation; that works in CFML but has a different meaning in JavaScript. |
- | Numeric subtraction, as you would expect. |
* | Numeric multiplication. |
/ | Numeric division. |
% | Modulus (remainder after division), like MOD in CFML. |
Understanding the Core Objects
JavaScript also provides a number of built-in objects, often called the core objects. Many of these objects represent data types, like String or Date. Table 17.6 lists some of the most commonly used core objects, many of which you will see used throughout this chapter. Consult a JavaScript reference for a complete list of the methods and properties exposed by these objects.
OBJECT | DESCRIPTION |
---|---|
Array | Array objects expose helpful methods such as .reverse() and .sort(). The length of an array is available in the .length property. |
Date | Date objects provide various date-manipulation methods such as .getMonth() and .toLocaleString(). |
Math | You don't create instances of this object; instead you use its methods directly, as in Math.round(), Math.abs(), and Math.random(). |
Object | Use the Object type to create your own custom objects that hold whatever data you need. Creating a new object is very similar conceptually to creating a new structure with StructNew() in CFML. |
String | Any string object has a number of helpful methods, like .substring(), .toLowerCase(), .toUpperCase() , and .indexOf(), which is kind of like CFML's Find() function. The length of a string is available in the .length property. |
Understanding JavaScript's Relationship to Web Browsers
JavaScript was originally designed by Netscape as a simple, lightweight scripting language that would work well in Web browsers. As such, people often get a little bit confused, thinking that JavaScript is something that is exclusively used in browsers.Not so. JavaScript is a language that can be used in many different contexts, in browsers, on servers, and in many other types of applications. Here's a partial list of the places where JavaScript (the scripting language, not the <script> tag) can be used:
- Web browsers .
This remains the most obvious example, and the one that will be discussed directly in this chapter. - Email clients .
These days, many email clients are just extensions of each vendor's respective Web browser technology, and provide much of the same support for JavaScript. - Macromedia Flash applications .
Beginning with version 5, Flash movies are scripted using ActionScript, which is very similar to JavaScript. - Active Server Pages (ASP) pages .
Many people think of ASP pages as something that you can only write with Visual Basic style syntax (VBScript), but ASP pages can also be written with JScript, which is essentially yet another form of JavaScript. - Windows Scripting Host (WSH) scripts .
These scripts can be used to create macros that interact directly with the Windows shell. - Macromedia Dreamweaver , for creating tag editor dialogs and other custom extensions. HomeSite+ (formerly ColdFusion Studio) also exposes an extension API to JavaScript.
- ColdFusion , to the extent that CFScript bears a striking relationship to JavaScript. It can't really be considered compatible with JavaScript, since it doesn't include support for the core objects listed in Chapter 12, "ColdFusion Scripting".
NOTEI'm skipping over some rather acrimonious contentious history when I say that JScript, ActionScript, and CFScript are essentially synonyms for JavaScript. JavaScript came first, developed by Netscape for version 2.0 of their browser. The language was later turned over to a standards body and evolved into the open specification known as EMCAScript, upon which JScript and ActionScript are officially based upon. Okay, even that is an oversimplification. Regardless of history, and regardless of the relevance of standards, the real-world intent of JScript and ActionScript are clearly to look, feel, and otherwise work like JavaScript.So, while although JavaScript is most often used in Web browsers, that's not the only place where it can be used. That's an important point to understand, and which brings us to our next topic: understanding scripting object models.
Understanding Scripting Object Models
Because JavaScript is designed to be used in many different contexts (see the bulleted list in the previous section), the context-specific stuff is kept separate from the language itself. Everything relevant to the specific context (say, a Web page or a form if the context is a browser, or the position of the cursor if the context is Dreamweaver) is exposed to JavaScript in the form of a set of scriptable objects, or object model .So, within any given context, there are really to things to know and understand:
- The JavaScript language itself .
Think of the language as consisting mainly of the items listed in Table 17.1 through Table 17.5, plus the various operators and semantic elements like curly braces and semicolons. - The object model specific to the context .
Assuming that the context is a web Web browser, then the object model includes scriptable representations of browser and Web page concepts (like the URL for the current document, the size of the browser window, and information about the image and form fields on the page).
TIPIf it helps, think of JavaScript itself as the language used to talk to the browser, and the object model as what you talk about. The language, then, is just a way of speaking; the object model is the actual subject of your conversation.The JavaScript language is really pretty simple. It's the object model supported by each browser that can get pretty complicated and potentially confusing. While each browser and version supports more or less the same language (JavaScript, which hasn't changed very much over the years), the object model exposed to JavaScript can differ quite a bit between browsers and versions. The differences between the object models exposed by Netscape and Microsoft browsers, for instance, were wildly different during the 4.x and 5.x versions of the respective products. Version 6.0 brought the object models much closer together in terms of scope, functionality, and overall design. Going forward, you can expect most scripts to work identically in IE, Firefox, Netscape, Mozilla, and Opera, especially if you stay away from whatever the latest-and-greatest feature of the moment happens to be.
JavaScript Objects Available in Web Pages
The scripting object model exposes a large number of objects that you can control via script within each Web page. inn218 property (this is demonstrated briefly in Listing 17.12).