47
3 - 2 // => 1: subtraction
3 * 2 // => 6: multiplication
3 / 2 // => 1.5: division
points[1].x - points[0].x // => 1: more complicated operands work, too
"3" + "2" // => "32": + adds numbers, concatenates strings
// JavaScript defines some shorthand arithmetic operators
var count = 0; // Define a variable
count++; // Increment the variable
count--; // Decrement the variable
count += 2; // Add 2: same as count = count + 2;
count *= 3; // Multiply by 3: same as count = count * 3;
count // => 6: variable names are expressions, too.
// Equality and relational operators test whether two values are equal,
// unequal, less than, greater than, and so on. They evaluate to true or false.
var x = 2, y = 3; // These = signs are assignment, not equality tests
x == y // => false: equality
x != y // => true: inequality
x < y // => true: less-than
x <= y // => true: less-than or equal
x > y // => false: greater-than
x >= y // => false: greater-than or equal
"two" == "three" // => false: the two strings are different
"two" > "three" // => true: "tw" is alphabetically greater than "th"
false == (x > y) // => true: false is equal to false
// Logical operators combine or invert boolean values
(x == 2) && (y == 3) // => true: both comparisons are true. && is AND
(x > 3) || (y < 3) // => false: neither comparison is true. || is OR
!(x == y) // => true: ! inverts a boolean value
If the phrases of JavaScript are expressions, then the full sentences are statements, which
are the topic of Chapter 5, Statements. In the code above, the lines that end with
semicolons are statements. (In the code below, you’ll see multiline statements that do
not end with semicolons.) There is actually a lot of overlap between statements and
expressions. Roughly, an expression is something that computes a value but doesn’t
do anything: it doesn’t alter the program state in any way. Statements, on the other
hand, don’t have a value (or don’t have a value that we care about), but they do alter
the state. You’ve seen variable declarations and assignment statements above. The
other broad category of statement is control structures, such as conditionals and loops.
Examples are below, after we cover functions.
A function is a named and parametrized block of JavaScript code that you define once,
and can then invoke over and over again. Functions aren’t covered formally until
Chapter 8, Functions, but like objects and arrays, you’ll see them many times before
you get to that chapter. Here are some simple examples:
// Functions are parameterized blocks of JavaScript code that we can invoke.
function plus1(x) { // Define a function named "plus1" with parameter "x"
return x+1; // Return a value one larger than the value passed in
} // Functions are enclosed in curly braces
6 | Chapter 1: Introduction to JavaScript
49
plus1(y) // => 4: y is 3, so this invocation returns 3+1
var square = function(x) { // Functions are values and can be assigned to vars
return x*x; // Compute the function's value
}; // Semicolon marks the end of the assignment.
square(plus1(y)) // => 16: invoke two functions in one expression
When we combine functions with objects, we get methods:
// When functions are assigned to the properties of an object, we call
// them "methods". All JavaScript objects have methods:
var a = []; // Create an empty array
a.push(1,2,3); // The push() method adds elements to an array
a.reverse(); // Another method: reverse the order of elements
// We can define our own methods, too. The "this" keyword refers to the object
// on which the method is defined: in this case, the points array from above.
points.dist = function() { // Define a method to compute distance between points
var p1 = this[0]; // First element of array we're invoked on
var p2 = this[1]; // Second element of the "this" object
var a = p2.x-p1.x; // Difference in X coordinates
var b = p2.y-p1.y; // Difference in Y coordinates
return Math.sqrt(a*a + // The Pythagorean theorem
b*b); // Math.sqrt() computes the square root
};
points.dist() // => 1.414: distance between our 2 points
Now, as promised, here are some functions whose bodies demonstrate common Java-
Script control structure statements:
// JavaScript statements include conditionals and loops using the syntax
// of C, C++, Java, and other languages.
function abs(x) { // A function to compute the absolute value
if (x >= 0) { // The if statement...
return x; // executes this code if the comparison is true.
} // This is the end of the if clause.
else { // The optional else clause executes its code if
return -x; // the comparison is false.
} // Curly braces optional when 1 statement per clause.
} // Note return statements nested inside if/else.
function factorial(n) { // A function to compute factorials
var product = 1; // Start with a product of 1
while(n > 1) { // Repeat statements in {} while expr in () is true
product *= n; // Shortcut for product = product * n;
n--; // Shortcut for n = n - 1
} // End of loop
return product; // Return the product
}
factorial(4) // => 24: 1*4*3*2
function factorial2(n) { // Another version using a different loop
var i, product = 1; // Start with 1
for(i=2; i <= n; i++) // Automatically increment i from 2 up to n
product *= i; // Do this each time. {} not needed for 1-line loops
return product; // Return the factorial
1.1 Core JavaScript | 7
43
}
factorial2(5) // => 120: 1*2*3*4*5
JavaScript is an object-oriented language, but it is quite different than most. Chapter 9,
Classes and Modules, covers object-oriented programming in JavaScript in detail, with
lots of examples, and is one of the longest chapters in the book. Here is a very simple
example that demonstrates how to define a JavaScript class to represent 2D geometric
points. Objects that are instances of this class have a single method named
r()
that
computes the distance of the point from the origin:
// Define a constructor function to initialize a new Point object
function Point(x,y) { // By convention, constructors start with capitals
this.x = x; // this keyword is the new object being initialized
this.y = y; // Store function arguments as object properties
} // No return is necessary
// Use a constructor function with the keyword "new" to create instances
var p = new Point(1, 1); // The geometric point (1,1)
// Define methods for Point objects by assigning them to the prototype
// object associated with the constructor function.
Point.prototype.r = function() {
return Math.sqrt( // Return the square root of x² + y²
this.x * this.x + // This is the Point object on which the method...
this.y * this.y // ...is invoked.
);
};
// Now the Point object p (and all future Point objects) inherits the method r()
p.r() // => 1.414...
Chapter 9 is really the climax of Part I, and the chapters that follow wrap up some loose
ends and bring our exploration of the core language to a close. Chapter 10, Pattern
Matching with Regular Expressions, explains the regular expression grammar and dem-
onstrates how to use these “regexps” for textual pattern matching. Chapter 11, Java-
Script Subsets and Extensions, covers subsets and extensions of core JavaScript. Finally,
before we plunge into client-side JavaScript in web browsers, Chapter 12, Server-Side
JavaScript, introduces two ways to use JavaScript outside of web browsers.
1.2 Client-Side JavaScript
Client-side JavaScript does not exhibit the nonlinear cross-reference problem nearly to
the extent that the core language does, and it is possible to learn how to use JavaScript
in web browsers in a fairly linear sequence. But you’re probably reading this book to
learn client-side JavaScript, and Part II is a long way off, so this section is a quick sketch
of basic client-side programming techniques, followed by an in-depth example.
Chapter 13, JavaScript in Web Browsers, is the first chapter of Part II and it explains in
detail how to put JavaScript to work in web browsers. The most important thing you’ll
8 | Chapter 1: Introduction to JavaScript
50
learn in that chapter is that JavaScript code can be embedded within HTML files using
the
<script>
tag:
<html>
<head>
<script src="library.js"></script> <!-- include a library of JavaScript code -->
</head>
<body>
<p>This is a paragraph of HTML</p>
<script>
// And this is some client-side JavaScript code
// literally embedded within the HTML file
</script>
<p>Here is more HTML.</p>
</body>
</html>
Chapter 14, The Window Object, explains techniques for scripting the web browser and
covers some important global functions of client-side JavaScript. For example:
<script>
function moveon() {
// Display a modal dialog to ask the user a question
var answer = confirm("Ready to move on?");
// If they clicked the "OK" button, make the browser load a new page
if (answer) window.location = "http://google.com";
}
// Run the function defined above 1 minute (60,000 milliseconds) from now.
setTimeout(moveon, 60000);
</script>
Note that the client-side example code shown in this section comes in longer snippets
than the core language examples earlier in the chapter. These examples are not designed
to be typed into a Firebug (or similar) console window. Instead you can embed them
in an HTML file and try them out by loading them in your web browser. The code
above, for instance, works as a stand-alone HTML file.
Chapter 15, Scripting Documents, gets down to the real business of client-side Java-
Script, scripting HTML document content. It shows you how to select particular HTML
elements from within a document, how to set HTML attributes of those elements, how
to alter the content of those elements, and how to add new elements to the document.
This function demonstrates a number of these basic document searching and modifi-
cation techniques:
// Display a message in a special debugging output section of the document.
// If the document does not contain such a section, create one.
function debug(msg) {
// Find the debugging section of the document, looking at HTML id attributes
var log = document.getElementById("debuglog");
// If no element with the id "debuglog" exists, create one.
if (!log) {
log = document.createElement("div"); // Create a new <div> element
log.id = "debuglog"; // Set the HTML id attribute on it
1.2 Client-Side JavaScript | 9
58
log.innerHTML = "<h1>Debug Log</h1>"; // Define initial content
document.body.appendChild(log); // Add it at end of document
}
// Now wrap the message in its own <pre> and append it to the log
var pre = document.createElement("pre"); // Create a <pre> tag
var text = document.createTextNode(msg); // Wrap msg in a text node
pre.appendChild(text); // Add text to the <pre>
log.appendChild(pre); // Add <pre> to the log
}
Chapter 15 shows how JavaScript can script the HTML elements that define web con-
tent. Chapter 16, Scripting CSS, shows how you can use JavaScript with the CSS styles
that define the presentation of that content. This is often done with the
style
or
class
attribute of HTML elements:
function hide(e, reflow) { // Hide the element e by scripting its style
if (reflow) { // If 2nd argument is true
e.style.display = "none" // hide element and use its space
}
else { // Otherwise
e.style.visibility = "hidden"; // make e invisible, but leave its space
}
}
function highlight(e) { // Highlight e by setting a CSS class
// Simply define or append to the HTML class attribute.
// This assumes that a CSS stylesheet already defines the "hilite" class
if (!e.className) e.className = "hilite";
else e.className += " hilite";
}
JavaScript allows us to script the HTML content and CSS presentation of documents
in web browsers, but it also allows us to define behavior for those documents with
event handlers. An event handler is a JavaScript function that we register with the
browser and the browser invokes when some specified type of event occurs. The event
of interest might be a mouse click or a key press (or on a smart phone, it might be a
two-finger gesture of some sort). Or an event handler might be triggered when the
browser finishes loading a document, when the user resizes the browser window, or
when the user enters data into an HTML form element. Chapter 17, Handling Events,
explains how you can define and register event handlers and how the browser invokes
them when events occur.
The simplest way to define event handlers is with HTML attributes that begin with
“on”. The “onclick” handler is a particularly useful one when you’re writing simple
test programs. Suppose that you had typed in the
debug()
and
hide()
functions from
above and saved them in files named debug.js and hide.js. You could write a simple
HTML test file using
<button>
elements with
onclick
event handler attributes:
<script src="debug.js"></script>
<script src="hide.js"></script>
Hello
<button onclick="hide(this,true); debug('hide button 1');">Hide1</button>
10 | Chapter 1: Introduction to JavaScript
49
<button onclick="hide(this); debug('hide button 2');">Hide2</button>
World
Here is some more client-side JavaScript code that uses events. It registers an event
handler for the very important “load” event, and it also demonstrates a more sophis-
ticated way of registering event handler functions for “click” events:
// The "load" event occurs when a document is fully loaded. Usually we
// need to wait for this event before we start running our JavaScript code.
window.onload = function() { // Run this function when the document loads
// Find all <img> tags in the document
var images = document.getElementsByTagName("img");
// Loop through them, adding an event handler for "click" events to each
// so that clicking on the image hides it.
for(var i = 0; i < images.length; i++) {
var image = images[i];
if (image.addEventListener) // Another way to register a handler
image.addEventListener("click", hide, false);
else // For compatibility with IE8 and before
image.attachEvent("onclick", hide);
}
// This is the event handler function registered above
function hide(event) { event.target.style.visibility = "hidden"; }
};
Chapters 15, 16, and 17 explain how you can use JavaScript to script the content
(HTML), presentation (CSS), and behavior (event handling) of web pages. The APIs
described in those chapters are somewhat complex and, until recently, riddled with
browser incompatibilities. For these reasons, many or most client-side JavaScript pro-
grammers choose to use a client-side library or framework to simplify their basic pro-
gramming tasks. The most popular such library is jQuery, the subject of Chapter 19,
The jQuery Library. jQuery defines a clever and easy-to-use API for scripting document
content, presentation, and behavior. It has been thoroughly tested and works in all
major browsers, including old ones like IE6.
jQuery code is easy to identify because it makes frequent use of a function named
$()
. Here is what the
debug()
function used previously looks like when rewritten to use
jQuery:
function debug(msg) {
var log = $("#debuglog"); // Find the element to display msg in.
if (log.length == 0) { // If it doesn't exist yet, create it...
log = $("<div id='debuglog'><h1>Debug Log</h1></div>");
log.appendTo(document.body); // and insert it at the end of the body.
}
log.append($("<pre/>").text(msg)); // Wrap msg in <pre> and append to log.
}
The four chapters of Part II described so far have all really been about web pages. Four
more chapters shift gears to focus on web applications. These chapters are not about
using web browsers to display documents with scriptable content, presentation, and
1.2 Client-Side JavaScript | 11
24
behavior. Instead, they’re about using web browsers as application platforms, and they
describe the APIs that modern browsers provide to support sophisticated client-side
web apps. Chapter 18, Scripted HTTP, explains how to make scripted HTTP requests
with JavaScript—a kind of networking API. Chapter 20, Client-Side Storage, describes
mechanisms for storing data—and even entire applications—on the client side for use
in future browsing sessions. Chapter 21, Scripted Media and Graphics, covers a client-
side API for drawing arbitrary graphics in an HTML
<canvas>
tag. And, finally, Chap-
ter 22, HTML5 APIs, covers an assortment of new web app APIs specified by or affiliated
with HTML5. Networking, storage, graphics: these are OS-type services being provided
by the web browser, defining a new cross-platform application environment. If you are
targeting browsers that support these new APIs, it is an exciting time to be a client-side
JavaScript programmer. There are no code samples from these final four chapters here,
but the extended example below uses some of these new APIs.
1.2.1 Example: A JavaScript Loan Calculator
This chapter ends with an extended example that puts many of these techniques to-
gether and shows what real-world client-side JavaScript (plus HTML and CSS) pro-
grams look like. Example 1-1 lists the code for the simple loan payment calculator
application pictured in Figure 1-2.
Figure 1-2. A loan calculator web application
It is worth reading through Example 1-1 carefully. You shouldn’t expect to understand
everything, but the code is heavily commented and you should be able to at least get
12 | Chapter 1: Introduction to JavaScript
Documents you may be interested
Documents you may be interested