Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > Ajax and JavaScript

An Orientation to JavaScript

In this sample chapter, Bill Sanders examines the nuances of JavaScript and gives you the basics for when you start writing your own scripts.
This sample chapter is excerpted from JavaScript Design, by Bill Sanders.
This chapter is from the book

This chapter is from the book

Writing JavaScript

As you saw in Chapter 1, "Jump-Starting JavaScript," JavaScript goes into an HTML page. However, you do not write JavaScript with the same abandon as you do HTML. Very specific and apparently minor differences exist between how HTML can be written and how JavaScript can be written. While the differences might appear to be minor or even trivial, if the rules for writing JavaScript are not followed, you can run into glitches. This chapter examines the nuances of JavaScript so that when you start writing your own scripts, you'll have all of the basics clear in your mind.

HTML is a markup language, and JavaScript is a programming or scripting language. HTML describes what is to be presented on a page, and JavaScript dynamically changes what is on an HTML page (among other tasks.) Both use code. HTML's code is in a series of angle brackets that describe how to treat the material between the opening and closing brackets. JavaScript is a set of statements and functions that does something in an HTML page. JavaScript can refer to and alter objects described by HTML.

Case Sensitivity

You can write HTML tags in just about any way you want, as long as you spell the tags correctly and remember to include the arrow bracket around the tags. For example, the following little page will work just fine in HTML:

<hTmL>
<heaD>
<Title>Do it your way</tITLE>
</HEAD>
<BoDY Bgcolor="HotPink">
<ceNTer>
<h1>
HTML is CaSe InSeNsItIvE!
</H1>
</bODY>
</HTML>

Just about every non–case-sensitive combination of characters that you can imagine has been put into that page. The opening tags of a container are in one case combination, and the closing tags are in another. Tags in one case are duplicated with tags in another case. For HTML, that's no problem. You don't have to pay attention to case at all.

JavaScript is the opposite. You have to pay attention to the cases of everything that you type in JavaScript because it is case-sensitive. The HTML around the script need not be case-sensitive, but the JavaScript itself must be. Consider the following examples. The first follows the rules of case sensitivity, and the second one does not.

<html>
<head>
<title>Case Sensitive</title>
<script language="JavaScript">
alert("Pay attention to your cases!");
</script>
</head>
<body bgcolor="moccasin">
<p>
<h1>Just in case!</h1>
</p>
</body>
</html>

When you load the page, you will see an alert message telling you to pay attention to your cases. As soon as you click the OK button on the alert box, the rest of the page appears with the message "Just in case." Now, look at this next script to see if you can tell where the error lies. It is slightly different from the first—only the a in "alert" has been changed so that it is "Alert." Just that little change will invalidate the JavaScript code. Launch the page with the capital A, and see what happens.

<html>
<head>
<title>Case Sensitive</title>
<script language="JavaScript">
Alert("Pay attention to your cases!");
</script>
</head>
<body bgcolor="moccasin">
<p>
<h1>Just in case!</h1>
</p>
</body>
</html>

As you saw, the page didn't crash and burn. It just ignored the JavaScript and went on and put up the page on the screen. I would rather see an error message issued so that I could see any problems that arise, but neither of the newest versions of the browsers indicated any trouble at all. (In Netscape Navigator 4.7, a little error message blinks in the lower-left corner, but it happens so fast that you cannot tell that your script has an error.) Debugging JavaScript is often a matter of not seeing what you expect on the screen rather than seeing any clue that you've coded your script incorrectly. However, ignoring case sensitivity is likely to be one bug in the code that you should suspect immediately.

For the most part, JavaScript is typed in lowercase fonts, but you will find many exceptions to that rule. In Chapter 1, you might have noticed the use of Math.floor along with toString in one of the scripts. Both of those words use a combination of upper- and lowercase fonts: intercase. Object, Math, Date, Number, and RegExp are among the objects that use case combinations as well. Properties such as innerHeight, outerWidth, and isFinite, likewise, are among the many other JavaScript terms using case combinations.

You also might run into cases differences in HTML and JavaScript. Event-related attributes in HTML such as onMouseOver, onMouseOut, and onClick are spelled with a combination of upper- and lowercase characters by convention, but, in JavaScript, you must use all lowercase on those same terms. Hence, you will see .onmouseover, .onmouseout, and .onclick.

Another area of case sensitivity in JavaScript can be found in naming variables and functions. You can use any combination of upper- and lowercase characters that you want in a function or variable name, as long as it begins with an ASCII letter, dollar sign, or underscore. Functions are names that you give to a set of other statements or commands. (See an introduction to functions in Chapter 1.) Variables are names that you give to containers that hold different values. For example, the variable customers might contain the words "John Davis" or "Sally Smith." Variables can contain words or numbers. (See the next chapter for a more detailed discussion of variables.) When the function or variable is given a name, you must use the same set of upper- and lowercase characters that you did when you declared the variable or functions. For example, the following script uses a combination of characters in both variables and function. When the function is fired, the name must be spelled as it is in the definition.

VarFuncCase.html

<html>
<head>
<title>Cases in Variables and Functions</title>
<script language="JavaScript">
var Tax=.05
function addTax(item) {
var Total=item + (item * Tax);
var NewTotal=Math.floor(Total);
var Fraction=Math.round(Total *100)%100;
if (Fraction<10) {
Fraction = "0" + Fraction;
}
Total=NewTotal +"." + Fraction;
alert("Your total is $" + Total);
}
</script>
</head>
<body bgcolor="palegreen">
<center><h2>
<a href=# onClick="addTax(7.22)";> Click for total
</a>
</body>
</html>

Several variables and two functions (the alert function is built in and so has a name already—alert) are included in the script, but notice that all of the variable names and function references use the same combination of upper- and lowercase characters. The string message for the alert function reads, "Your total is $" + Total);. The first use of total is part of a message (string literal) and is not a variable in this case. The Total attached to the end of the alert message, however, is a variable, and it uses the uppercase first letter as the variable does when it is defined. Likewise, the argument in the function (item) is always referenced in lowercase because it is initially written in lowercase. The variable declaration lines beginning with var signal the initial creation of a variable, and the case configuration used in those lines is the configuration that must be used throughout the page in reference to a given variable. Chapter 3, "Dealing with Data and Variables," explains developing variables in detail.

Figure 2.1 shows what you will see when the page loads and you click the link text. If you want a link to launch a JavaScript function, you can use a "dummy" link by inserting a pound sign (#) where the URL usually is placed. Then, by adding an event handler, you can launch the function. Try changing the value in the addTax() function to see what you get. Also, see what happens when you change addTax to ADDTAX().

Figure 2.1. None of HTML is case-sensitive, but virtually all of JavaScript is.

Entering Comments

Comments are messages to yourself and others who are working to develop a JavaScript program with you. They serve to let you know what the following lines of code do or, if incomplete, what you want them to do. Comments in JavaScript are entered by prefacing a line with double forward slashes (//). When the code is parsed in the browser, all of the lines beginning with the double slashes are ignored. For example, the following code segment shows a reminder to add tax to an item in an e-business application:

//Include a variable to add taxes
tax= .06
//Add the tax to the taxable item
item += item * tax

The bigger and more complex your scripts become, the more you will need to have well-commented code. Comments in code become even more crucial when you are working with a team to create a web site and others need to know what your code is doing. In this book, you will see comments throughout the code in the larger scripts to point out different elements. In shorter scripts, the comments are in the text of the book, a luxury that you will not have in your own coding. Remember to comment your code, and you will see that you can save a good deal of time reinventing a solution that is already completed.

The Optional Semicolon

Several languages that look a lot like JavaScript require a semicolon after lines. For example, Flash ActionScript and PHP (see Chapter 14, "Using PHP with JavaScript," and Chapter 18, "Flash ActionScript and JavaScript") both require semicolons. Likewise, compiled languages such as C++ and Java require semicolons at the end of lines. JavaScript made semicolons optional.

So, the question is, do you really need the semicolon? JavaScript places "invisible" semicolons at the end of each line, and by placing a visible semicolon, you can better see what's going on. For debugging your program, the semicolons alert you to where a line ends; if you did not intend a line to end where you put a semicolon, you can better see the error. Hence, the answer to the question of whether you should include semicolons is "yes."

Semicolons go at the end of lines that do not end in a curly brace or to separate variable declarations on the same line. For example, the following two code segments show where semicolons may optionally be placed.

function findIt() {
   if(x="searchWord") {
      document.formA.elementA.value=x;
   }
}

Because four of the five lines end in a curly brace, only the third line optionally can have a semicolon. On the other hand, in a list of variable definitions, you can place a semicolon at the end of every line.

var alpha="Apples";
var beta= alpha + "Oranges";
var gamma= Math.sqrt(omega);
var delta= 200/gamma;

Older Browsers

At the time of this writing, Netscape Navigator 6.01 is in general release for both Windows and Macintosh operating systems, and Internet Explorer has a Version 6 in public preview for Windows and is in Version 5.5 on the Macintosh. By the time this book is published, both major browsers will most likely have Version 6 as their standard browser. Keeping in mind that the browsers are the interpreters for JavaScript, the version of browser that others use to view your scripts is very important. Version 3 browsers will read most JavaScript, but not until Version 4 of the two major browsers was JavaScript 1.2 available. Therefore, you really need your viewers to have at least Version 4 of either major browser for use with code from JavaScript 1.2. A guy in Outer Mongolia with an Internet connection has the same access to a new browser as a guy in Silicon Valley; all he has to do is to download and install either browser for free.

However, to get around the holdout who thinks that technology ended with his Version 2 Netscape Navigator, you can enter a simple set of semitags to mask the JavaScript. Because the older browsers don't know JavaScript from Sanskrit, they think that the code is text to be displayed on the page. To hide the JavaScript, you can place the container made up of <!-- and //--> around the JavaScript code. For example, the following script segment is hidden from older browsers, and their parsers will skip over it:

<script language="JavaScript">
<!--
document.write("The old browsers cannot read this.")
//-->

Rarely do you find anyone still using browsers older than Version 4, and unless you want to degrade your JavaScript to an earlier version, you can include the masking container. However, at this point in browser development, it might be wiser to let the visitor know that her browser could use an upgrade by allowing JavaScript to appear on the screen. (A few cantankerous designers even use notes telling the viewer to upgrade his browser or get lost!)

Some designers attempt to write JavaScript with different sets of code for users with very old browsers by using browser-detection scripts written in JavaScript. In that way, users with older browsers can see some web page. In terms of cost benefits, having alternative sets of code for different browsers, different versions of browsers, and browsers for different platforms can become an onerous and expensive task. However, each designer/developer needs to decide her own willingness to have several different scripts for each page. With short scripts and a few pages, only a little extra work is required. However, with big sites and long sets of code, designers might find that they have to increase their time on the project and that they must charge their clients, or use the lowest common denominator of JavaScript.

Peachpit Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Peachpit and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about Peachpit products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites; develop new products and services; conduct educational research; and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email ask@peachpit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by Adobe Press. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.peachpit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020