BUY THIS BOOK
Add to Cart

Print Book $29.99


Safari Books Online

What is this?

Add to UK Cart

Print Book £20.99

What is this?

Looking to Reprint this content?


Learning JavaScript
Learning JavaScript By Shelley Powers
October 2006
Pages: 351

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Introduction and First Looks
JavaScript is one of the most widely used programming languages; it is also one of the most misunderstood. Its growth has exploded in the last few years, and most web sites use it in some form. Its component-based capabilities simplify the creation of increasingly complicated libraries—most providing effects in web pages that previously required the installation of an external application. It can also be tightly integrated with server-side applications that are created with a variety of languages and interface with any number of databases. Yet for all of this, JavaScript is often considered lightweight and unsophisticated—not like a “real” programming language.
In some ways, JavaScript is too easy to use. To its detractors, it lacks discipline; its object-oriented capabilities aren’t really OO; it exists within a simplified environment with only a subset of functionality; it isn’t secure; it’s loosely typed; it doesn’t compile into bytes or bits. I remember reading in a JavaScript introduction years ago that you shouldn’t let the name fool you: JavaScript has little to do with Java. After all, Java is hard to learn.
So what’s the reality? Is JavaScript a fun little scripting language—lightweight, helpful, but not to be taken seriously? Or is it a powerful programming language you can trust with some of your site’s most important functionality? The reality of JavaScript, and hence the confusion, is that it’s two languages in one.
The first is a friendly, easy-to-use scripting language built into web browsers and other applications, offering functions such as form validation and cool stuff like drop-down menus, color fades during data updates, and in-place page edits. Because it’s implemented within a specific environment—usually a web browser of some form—and within a protected environment, JavaScript doesn’t need to have functionality to manage files, memory, or many of the other programming language basic components, making it leaner and simpler. You can begin programming in JS with little or no background, training, or even prior programming experience.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Twisted History: Specs and Implementations
Learning a programming language doesn’t require learning its history—unless you’re a language like JavaScript, whose history is reflected in web pages today.
JavaScript originated with Netscape, back when it was first developing its LiveConnect server-side development. The company wanted a scripting language that could interface with the server-side components and created one called “LiveScript.” Later, after an initial partnership with Sun, owner of the Java programming language, the Netscape engineers renamed LiveScript to JavaScript, even though there was and is no connection between either programming language. Well-known JavaScript guru Steven Champeon wrote:
Rewind to early 1995. Netscape had just hired Brendan Eich away from MicroUnity Systems Engineering, to take charge of the design and implementation of a new language. Tasked with making Navigator’s newly added Java support more accessible to non-Java programmers, Eich eventually decided that a loosely typed scripting language suited the environment and audience, namely the few thousand web designers and developers who needed to be able to tie into page elements (such as forms, or frames, or images) without a bytecode compiler or knowledge of object-oriented software design.
The language he created was christened “LiveScript,” to reflect its dynamic nature, but was quickly (before the end of the Navigator 2.0 beta cycle) renamed JavaScript, a mistake driven by marketing that would plague web designers for years to come, as they confused the two incessantly on mailing lists and on Usenet. Netscape and Sun jointly announced the new language on December 4, 1995, calling it a “complement” to both HTML and Java.
(From “JavaScript: How Did We Get Here?” O’Reilly Network, April 2001.)
Not to be out-engineered, Microsoft countered Netscape’s effort with the release of Internet Explorer and its own scripting language—VBScript—derived from the company’s popular Visual Basic. Later, it also released its own version of a JavaScript-like language: JScript.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Cross-Browser Incompatibility and Other Common JavaScript Myths
The JavaScript language runs in multiple environments and on many platforms. It can be used to develop web pages (and other applications) that work in operating systems such as Mac OS X, Windows, and Linux. It doesn’t require any special download or installation, because JavaScript is built into whatever browser you decide to use.
Most browsers implement a common subset of the language, making most code quite compatible across browsers. This can lead to confusion: if the language implementation is similar, where do the issues of cross-browser incompatibilities arise?
Most cross-browser incompatibilities are based on differences in the underlying Document Object Model (DOM) exposed by the browser, rather than on the language itself. For instance, a JavaScript language object would be Date or String; it will remain a Date or a String whether implemented in Safari or Navigator. An instance of an object from the DOM would be the document object, which represents that portion of the browser that holds the web page. How these DOM objects are exposed and manipulated within the browser’s respective implementation of JavaScript (or ECMAScript) is what leads to cross-browser incompatibility.
Another area of confusion has to do with what in the web page is managed by JavaScript and what is managed through the use of Cascading Style Sheets (CSS). The most that JavaScript can do with an element in a page is create it, remove it, or alter its attributes. Among such attributes are those defined through the CSS style attribute.
CSS defines the look and even some of the behavior of elements within the web page. It can hide or show elements, change color or font, move, resize, or clip, and so on. How each browser implements CSS can vary, and this can also lead to some issues of cross-browser incompatibility. All JavaScript does, though, is alter an element’s CSS style attributes.
ECMAScript compliance asserts that all built-in JavaScript objects be the same, but some small variations can exist between browsers. However, for the most part, cross-browser problems in the past have been based on DOM or CSS differences.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
What You Can Do with JavaScript
JavaScript achieved early widespread use for simple tasks: validating form contents, or setting and retrieving cookies (small bits of information that persist even when the browser is closed). In the late 1990s, with the introduction of Dynamic HTML (DHTML), JavaScript was also used to provide a more dynamic user experience through drop-down menus and the like.
JavaScript’s popularity has grown—exploded, really—most recently because it is a key component in Ajax (Asynchronous JavaScript and XML), which promises to restructure the way web applications interact with users. Over time, many cross-platform problems have been resolved, and the language has become more sophisticated—so much so that JavaScript is no longer just a scripting language; it’s a full-featured programming language.
So what can you do with JavaScript? Well, for starters:
Validate form fields
Validate form input before submitting the contents to the server. This saves time and server resources, and provides immediate feedback.
Set and retrieve web cookies
Persist information such as usernames, account numbers, or preferences in a controlled, safe environment—saving users time the next time they access a site.
Dynamically alter the appearance of a page element
Provide feedback by highlighting incorrect form entries; increase the size of a section’s font based on the reader’s request.
Hide and show elements
Based on personal preference or user actions, show or hide page content, such as form elements, expanding writing, and changing the displayed size of an image.
Move elements about the page
Create a drop-down menu, or provide an animated cursor to accent page elements.
Capture user events and adjust the page accordingly
Based on keyboard or mouse actions, make a section of the page editable.
Scroll content
For larger images or content areas, provide a way to grab the element with a mouse or keyboard, and scroll it right or left, up or down.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
First Look at JavaScript: “Hello World!”
One reason JavaScript is so popular is that it’s relatively easy to add JavaScript to a web page. All you need to do, at a minimum, is to include HTML script tags in the page, provide the JavaScript language for the type attribute, and add whatever JavaScript you want:
<script type="text/javascript">
...some JavaScript
</script>
Traditionally, script tags are added to the head element in the document (delimited by opening and closing head tags), but they can also be included in the body element—or even in both sections.
Example 1-1 shows a complete, valid web page, including a JavaScript block that uses the built-in alert function to open a message box containing the “Hello, World!” text.
Example . JavaScript block in the document head
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Example 1-1</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<script type="text/javascript">
   var dt = Date(  );

   // say hello to the world
   var msg = 'Hello, World! Today is ' + dt;
   alert(msg);
</script>
</head>
<body>
</body>
</html>
Copying this into a file and opening the file in any web browser should result in a box popping up as soon as the page as loaded. If it doesn’t, chances are that JavaScript is disabled in the browser, or, something very rare these days, that JavaScript isn’t supported.
Though the example is simple, it does expose the basic components of most JavaScript applications in use today. It deserves a closer look.
The examples in this book were all designed to validate as XHTML, which means that they include DOCTYPE, document title, and content type. You can discard these when recreating the examples. However, a better approach might be to create a skeleton web page including the DOCTYPE, title, content type, head, and body, and then copy it for most of the examples.
JavaScript, unlike some other languages, is almost always embedded within the context of another language, such as HTML and XHTML (both of which are actual languages, though the moving parts may not be as obvious). By this I mean that there are restrictions in how the script is added to the page. You can’t just plop JS into the page wherever and however you want.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The JavaScript Sandbox
When JavaScript was first released, there was understandable concern about opening a web page that would execute a bit of code directly in your machine. What if the JavaScript included something harmful, such as code to delete all Word documents or worse, copy them for the script originator?
To prevent such occurrences and to reassure browser users, JavaScript was built to operate in a sandbox: a protected environment in which the script can’t access the resources of the browser’s computer.
In addition, browsers implement security conditions above and beyond those established as a minimum for the JavaScript language. These are defined in a browser-specific security policy, which determines what the script can and cannot do. One such security policy dictates that a script may not communicate with pages other than those from the same domain where the script originated. Most browsers provide the means to customize this policy even further, making the environment in which the script operates more, or less, restrictive.
Unfortunately, even with the JavaScript sandbox and browser security policies, JavaScript has had a rough time, and hackers have discovered and exploited several JavaScript errors—some browser-dependent, some not. One of the more serious is known as cross-site scripting (XSS). This is actually a class of security breaks (some coming through JavaScript, others through holes in the browsers, and still others through the server) that can lead to cookie theft and exposure of client or site data and a host of other serious problems.
We’ll look at this later in much more detail, as well as how to prevent XSS, along with other security problems and preventions, and that infamous little goodie, the cookie, in Chapter 8.
The CERT site is the most authoritative on security issues, and the page discussing XSS can be found at http://www.cert.org/advisories/CA-2000-02.html. The CGISecurity.com site has an in-depth FAQ on XSS and can be found at
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Accessibility and JavaScript Best Practices
In an ideal world, everyone who visits your web site would use the same type of operating system and browser, and have JavaScript enabled. Your site would never be accessed via mobile phone or other odd-sized device; blind people wouldn’t need screen readers, and the paralyzed wouldn’t need voice-enabled navigation.
This isn’t an ideal world, but too many JS developers code as if it is. We get so caught up in the wonders of what we can create that we forget that not everyone can share them.
There are many best practices associated with JavaScript, but if there’s one to take away from this book, it’s the following: whatever JavaScript functionality you create, it must not come between your site and your site’s visitors.
What do I mean by “come between your site and your site’s visitors”? Avoid using JavaScript in such a way that those who cannot, or will not, enable JavaScript are prevented from accessing essential site resources using a nonscript-enabled browser. If you create a drop-down menu using JS, you also need to provide navigation for people not using a JS-enabled device. If your visitors are blind, JS must not interfere with audio browsers; if your visitors use a cellphone with a black and white screen, or they are color blind, your page shouldn’t depend on color to provide feedback.
Many developers don’t follow these practices because they assume the practices require extra work, and for the most part, they do. However, the work doesn’t have to be a burden—not when the results can increase the accessibility of your site. In addition, many companies now require that their web sites meet a certain level of accessibility. It’s better to get into the habit of creating accessible pages in the beginning than to try to fix the pages, or your habits, later.
The WebAIM site (http://www.webaim.org) has a wonderful tutorial on creating accessible JavaScript (available at http://www.webaim.org/techniques/javascript/). It covers the ways you shouldn’t use JavaScript, such as using JS for menus and other navigation. However, the site also provides ways you can use JS to make a site more accessible.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: JavaScript Data Types and Variables
The best part of JavaScript is that it’s forgiving, especially in regards to data typing. If you start out with a string and then want to use it as a number, that’s perfectly fine with the language. (Well, as long as the string actually contains a number and not something like an email address.) If you later want to treat it as a string again, that’s fine, too.
One could also say that the forgiving nature of JavaScript is one of the worst aspects of the language. If you try to add two numbers together, but the JavaScript engine interprets the variable holding one of them as a string data type, you end up with an odd string, rather than the sum you were expecting.
Context is everything when it comes to JavaScript data typing, and also when it comes to working with the most basic of JavaScript elements: the variable.
This chapter covers the three basic JavaScript data types: string, boolean, and number. Along the way, we’ll explore escape sequences in strings and take a brief look at Unicode. The chapter also delves into the topic of variables, including variable scope and what makes valid and meaningful variable identifiers. We’ll also look at the influences on identifiers that originate from the newest generation of JavaScript applications based on Ajax.
JavaScript variables have an identifier, scope, and a specific data type. Because the language is loosely typed, the rest, as they say, is subject to change without notice.
Variables in JavaScript are much like those in any other language; they’re used to hold values in such a way that the value can be explicitly accessed in different places in the code. Each has an identifier unique to the scope of use (more on this later), consisting of any combination of letters, digits, underscores, and dollar signs. There is no required format for an identifier, other than that it must begin with a character, dollar sign, or underscore:
_variableidentifier
variableIdentifier
$variable_identifier
var_ident
Starting with JavaScript 1.5, you can also use Unicode letters (such as &#252;) and digits, as well as escape sequences (such as \u0009) in variable identifiers. The following are also valid variable identifiers for JS:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Identifying Variables
JavaScript variables have an identifier, scope, and a specific data type. Because the language is loosely typed, the rest, as they say, is subject to change without notice.
Variables in JavaScript are much like those in any other language; they’re used to hold values in such a way that the value can be explicitly accessed in different places in the code. Each has an identifier unique to the scope of use (more on this later), consisting of any combination of letters, digits, underscores, and dollar signs. There is no required format for an identifier, other than that it must begin with a character, dollar sign, or underscore:
_variableidentifier
variableIdentifier
$variable_identifier
var_ident
Starting with JavaScript 1.5, you can also use Unicode letters (such as &#252;) and digits, as well as escape sequences (such as \u0009) in variable identifiers. The following are also valid variable identifiers for JS:
_&#252;valid
T\u0009
JavaScript is case-sensitive, treating upper- and lowercase characters as different characters. The following two variable identifiers are seen as separate variables in JS:
strngVariable
strngvariable
In addition, a variable identifier can’t be a JavaScript keyword, a list of which is illustrated in Table 2-1. Other keywords will be added over time, as new versions of JavaScript (well, technically ECMAScript) are released.
Table : JavaScript keywords
break
else
new
var
case
finally
return
void
catch
for
switch
while
continue
function
this
with
default
if
throw
delete
in
try
do
instanceof
typeof
Due to proposed extensions to the ECMA 262 specification, the words in Table 2-2 are also considered reserved.
Table : ECMA 262 specification reserved words
abstract
enum
int
short
boolean
export
interface
static
byte
extends
long
super
char
final
native
synchronized
class
float
package
throws
const
goto
private
transient
debugger
implements
protected
volatile
double
import
public
In addition to the ECMAScript reserved words, there are JavaScript-specific words implemented in most browsers that are considered reserved by implementation. Many are based in the Browser Object Model—objects such as
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Scope
The next critical characteristic of a variable is its scope: whether it’s local to a specific function or global to the entire JavaScript application. A variable with local scope is one that’s defined, initialized, and used within a function; when the function terminates, the variable ceases to exist. A global variable, on the other hand, can be accessed anywhere within any JavaScript contained within a web page—whether the JS is embedded directly in the page or imported through a JavaScript library.
In Chapter 1, I mentioned that there is no special syntax necessary to specifically define a variable. A variable can be both created and instantiated in the same line of code, and it need not look any different from a typical assignment statement:
num_value = 3.5;
This is a better approach:
var num_value = 3.5;
The difference between the two is the use of the var keyword.
Though not required, explicitly defining a variable using the var keyword is strongly recommended; doing so with local variables helps prevent collision between local and global variables of the same name. If a variable is explicitly defined in a function, its scope is restricted to the function, and any reference to that variable within the function is understood by both developer and JavaScript engine to be that local variable. With the growing popularity of larger, more complex JS libraries, using var prevents the unexpected side effects created by using what you think is a local variable, only to find out it’s global in scope.
To illustrate this type of side effect and the importance of explicitly declaring variables, Example 2-1 demonstrates a web page with separate blocks of JavaScript, each accessing the same variable, message. The page includes two external JavaScript files, both of which also set the same variable: one, globally, outside the function that uses it; the other, locally, within the function. None of the examples use the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Simple Types
JavaScript is a trim language, with just enough functionality to do the job—no more, no less. However, as I’ve said before, it is a confusing language in some respects.
For instance, there are just three simple data types: string, numeric, and boolean. Each is specifically differentiated by the literal it contains: string, numeric, and boolean. However, there are also built-in objects known as number, string, and boolean. These would seem to be the same thing, but aren’t: the first three are classifications of primitive values, while the latter three are complex constructions with a type of their own: object.
Rather than mix type and object, in the next three sections, we’ll look at each of the simple data types, how they’re created, and how values of one type can be converted to others. In Chapter 4, we’ll look at these and other built-in JS objects, and the methods and properties accessible with each.
A string variable was demonstrated in Example 2-1. Since JavaScript is a loosely typed language, there isn’t anything to differentiate it from a variable that’s a number or a boolean, other than the literal value assigned it when it’s initialized and the context of the use.
A string literal is a sequence of characters delimited by single or double quotes:
"This is a string"
'But this is also a string'
There is no rule as to which type of quote you use, except that the ending quote character must be the same as the beginning one. Any variation of characters can be included in the string:
"This is 1 string."
"This is--another string."
Not all characters are treated equally within a string in JavaScript. A string can also contain an escape sequence, such as \\n for end-of-line terminator.
An escape sequence is a set of characters in which certain characters are encoded in order to include them within the string. The following snippet of code assigns a string literal containing a line-terminator escape sequence to a variable. When the string is used in a dialog window, the escape sequence,
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Constants: Named but Not Variables
There are times when you’ll want to define a value once, and then have it treated as a read-only value from that time forward. The keyword const is used to create a JavaScript const:
const CURRENT_MONTH = 3.5;
The constant can be of any value, and since it can’t be assigned or reassigned a value at a later time, it’s initialized to its constant value when defined.
Just as with variables, a JavaScript constant has global and local scope. I use constants at a global level, primarily because they contain a value I want to be accessible (and unchanged) by a JavaScript block.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Questions
  1. Of the following identifiers, which are valid, which are not, and why?
    $someVariable
    _someVariable
    1Variable
    some_variable
    som&#232;variable
    function
    .someVariable
    some*variable
  2. Convert the following identifiers using the conventions outlined in the first section of the chapter:
    var some_month;
    function theMonth // function to return current month
    current-month // a constant
    var summer_month; // an array of summer months
    MyLibrary-afunction // a function from a JavaScript package 
  3. Is the following string literal valid? If not, how would you fix it?
    var someString = ‘Who once said, “Only two things are infinite, the universe and human stupidity, and I’m not sure about the former.”’
  4. Given a number, 432.54, what JavaScript returns the integer component of the number, and then finds the hexadecimal and octal conversion?
  5. You create a JavaScript function in a library that can be used by other applications. A parameter, someMonth, is passed to the function. How would you determine whether it’s null or undefined?
Answers are provided in the appendix.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Operators and Statements
The examples in the book so far have performed mostly simple tasks: a variable has been defined and its value set; a value is printed out in the page or in an alert window; a variable is modified through addition or multiplication or some other means. These all use JavaScript statements and operators.
There are a number of different types of statements in JavaScript: assignment, function call, conditional, and loops. Each is fairly intuitive, simple to use, and quick to learn. A snap, really. As with with most programming languages, in JavaScript the statements are easy to learn; the tricky part is lining them up, one after the other, so they do something useful.
This chapter takes a closer look at statements and operators, what they share, and how they differ.
JavaScript statements terminate with a semicolon, though not all statements need the terminator expressly given. If the JavaScript engine determines that a statement is complete (whatever that is for each type of statement), and the line ends with a new line character, the semicolon can be omitted:
var bValue = true
var sValue = "this is also true"
If multiple statements are on the same line, though, the semicolon must be used to terminate each:
var bValue = true; var sValue = "this is also true";
However, not explicitly terminating each JavaScript statement is a bad habit to get into, and one that can result in unexpected consequences. As such, the use of the semicolon to terminate JavaScript statements is a JavaScript best practice.
JavaScript Best Practice: Explicitly terminate JavaScript statements with the semicolon, whether or not it’s required.
The use of whitespace in JS has little impact on the code. For instance, the following two lines of code are interpreted exactly the same:
var firstName = 'Shelley'     ;
var firstName = 'Shelley';
Other than to delimit words within quotes or to terminate statements, extra whitespace—such as tabs, spaces, and new lines—is disregarded. In the following code, the variable assignment completes successfully, even though there is a line terminator separating the statement:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Format of a JavaScript Statement
JavaScript statements terminate with a semicolon, though not all statements need the terminator expressly given. If the JavaScript engine determines that a statement is complete (whatever that is for each type of statement), and the line ends with a new line character, the semicolon can be omitted:
var bValue = true
var sValue = "this is also true"
If multiple statements are on the same line, though, the semicolon must be used to terminate each:
var bValue = true; var sValue = "this is also true";
However, not explicitly terminating each JavaScript statement is a bad habit to get into, and one that can result in unexpected consequences. As such, the use of the semicolon to terminate JavaScript statements is a JavaScript best practice.
JavaScript Best Practice: Explicitly terminate JavaScript statements with the semicolon, whether or not it’s required.
The use of whitespace in JS has little impact on the code. For instance, the following two lines of code are interpreted exactly the same:
var firstName = 'Shelley'     ;
var firstName = 'Shelley';
Other than to delimit words within quotes or to terminate statements, extra whitespace—such as tabs, spaces, and new lines—is disregarded. In the following code, the variable assignment completes successfully, even though there is a line terminator separating the statement:
var firstName 
= 'Shelley';
alert(firstName);
The engine didn’t interpret the end-of-line character as a statement terminator in this instance because it evaluated the code and determined that it was incomplete. The JavaScript engine continues to process what it finds until either the semicolon is reached or until a statement is completed. In the case of the assignment statement, this state is reached when the right-side expression of the statement is provided.
Deciding whether to interpret an end-of-line terminator as a statement terminator is all a part of JavaScript’s forgiving nature: JavaScript works on the side of successfully processing the code and does whatever is needed to facilitate this. Well, unless doing so introduces confusion. In the following code:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Simple Statements
Some JavaScript statements extend beyond a line, such as those for loops, which have a beginning and end. Others, though, stand all on their own: one statement, one line. Among these simple statements are those for assignment.
The most common statement is the assignment statement. It’s an expression consisting of a variable on the left side, an assignment operator (=), and whatever is being assigned on the right.
The expression on the right can be a literal value:
nValue = 35.00;
Or, a combination of variables and literals combined with any number of operators:
nValue = nValue + 35.00;
And it can be a function call:
nValue = someFunction(  );
More than one assignment can be included on a line. For instance, the following assigns the value of an empty string to multiple variables, on one line:
Following the assignment statement, the second most common type of statement is the arithmetic expression that involves the arithmetic operators, discussed next.
In the last section, the second example was a demonstration of a binary arithmetic expression: two operands are separated by an arithmetic operator, leading to a new result. When paired with an assignment, the result is then assigned to the variable on the left:
nValue = vValue + 35.00;
More complex examples can use any number of arithmetic operators, with any combination of literal values and variables:
nValue = nValue + 30.00 /  2 - nValue2 * 3;
The operators used in the expression come from this set of binary operators:
+
For addition
-
For subtraction
*
For multiplication
/
For division
%
To return the remainder after division
These are considered binary operators because they require two operands, one on either side of the operator. Any number can be combined into one statement and assigned to one variable:
var bigCalc = varA * 6.0 + 3.45 - varB / .05;
This code shows the binary operators working with numbers. How about if the values are strings?
In some of the previous examples, I
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Conditional Statements and Program Flow
Normally in JavaScript, the program flow is linear: each statement is processed in tur

Return to Learning JavaScript