Lesson 20

Getting Started with JavaScript Programming

What You’ll Learn in This Lesson:

  • Image How and why to organize scripts using functions

  • Image What objects are and how JavaScript uses them

  • Image How JavaScript can respond to events

  • Image How and when to use conditional statements and loops

  • Image How browsers execute scripts in the proper order

  • Image Basic syntax rules for avoiding JavaScript errors

  • Image What JSON is and how it can be used

The preceding lesson reminded you of some of the basic uses of JavaScript and how to include JavaScript in your HTML documents. In this lesson, you’ll learn a few more basic JavaScript concepts and script components that you’ll use in just about every bit of JavaScript script you write. In addition, you’ll learn about JSON (JavaScript Object Notation), which provides a simple structured way to store information that can be used on the client side. Understanding these components will prepare you for the remaining lessons, in which you’ll explore specific JavaScript functions and features in greater depth.

Basic Concepts

There are a few basic concepts and terms you’ll run into throughout these lessons. In the following sections, you’ll learn about the basic building blocks of JavaScript.

Statements

Statements are the basic units of a JavaScript program. A statement is a section of code that performs a single action. For example, the following four statements are from the date and time example in Lesson 4, “Understanding JavaScript”:

now = new Date();
hours = now.getHours();
mins = now.getMinutes();
secs = now.getSeconds();

These statements create a new Date object and then assign the values for the current hour, minutes, and seconds into variables called hours, mins, and secs, respectively. You can then use these variables in your JavaScript code.

Although a statement is typically a single line of JavaScript, it is not a rule that it has to be. It’s possible (and fairly common) to break a statement across multiple lines or to include more than one statement in a single line.

A semicolon marks the end of a statement, but you can also omit the semicolon if you start a new line after the statement—if that is your coding style. For example, these are three valid JavaScript statements:

hours = now.getHours()
mins = now.getMinutes()
secs = now.getSeconds()

Caution

While omitting the semicolon is valid, many JavaScript errors are caused by missing semicolons. It’s best to get in the habit of always using semicolons at the end of statements to reduce errors.

However, if you combine statements into a single line, you must use semicolons to separate them. For example, the following line is valid:

hours = now.getHours(); mins = now.getMinutes(); secs = now.getSeconds();

This line is invalid:

hours = now.getHours() mins = now.getMinutes() secs = now.getSeconds();

Combining Tasks with Functions

A function is a number of JavaScript statements that are treated as a single unit. A statement that uses a function is referred to as a function call. For example, you might create a function called alertMe, which produces an alert when called, like so:

function alertMe() {
   alert("I am alerting you!");
}

When this function is called, a JavaScript alert pops up, and the text “I am alerting you” is displayed in a box, as shown in Figure 20.1.

A screenshot shows a web page with a link reading Click here at the top left and overlapped by an alert box reading "I am alerting you" with an "OK" button.
Figure 20.1 An alert box on a web page.

A function can take a parameter—an expression inside the parentheses—that tells the function what to do. In addition, a function can return a value to a waiting variable. For example, the following function call prompts the user for a response and stores it in the text variable:

text = prompt("Enter some text.")

Creating your own functions is useful for two main reasons. First, you can separate logical portions of your script to make it easier to understand. Second, and more importantly, you can use the function several times or with different data to avoid repeating script statements.

Variables

If you recall the basic introduction to JavaScript in Lesson 4, you’ll remember that a variable is a container that can store a number, a string of text, or another value. For example, the following statement creates a variable called fred and assigns it the value 27:

var fred = 27;

JavaScript variables can contain numbers, text strings, and other values. You’ll learn more about variables in much greater detail in Lesson 22, “Using JavaScript Variables, Strings, and Arrays.”

Understanding Objects

JavaScript also supports objects. Like variables, objects can store data—but they can store two or more pieces of data at once. As you’ll learn throughout the JavaScript-specific lessons in this course, using built-in objects and their methods is fundamental to JavaScript; it’s one of the ways the language works, by providing a predetermined set of actions you can perform. For example, with the document.write functionality you saw in Lesson 19, “Understanding Dynamic Websites and HTML5 Applications,” you can use the write method of the document object to output text to the browser for eventual rendering.

The data stored in an object are called the properties of the object. For example, you could use objects to store information about people in an address book. The properties of each person object might include a name, an address, and a telephone number.

You should become intimately familiar with object-related syntax because you will see objects quite a lot, even if you don’t build your own. You’ll definitely find yourself using built-in objects, and objects will very likely form a large part of any JavaScript libraries you import for use. JavaScript uses periods to separate object names and property names. For example, for a person object called Bob, the properties might include Bob.address and Bob.phone.

Objects can also include methods. A method is a function that works with an object’s data. For example, our person object for the address book might include a display() method to display the person’s information. In JavaScript terminology, the statement Bob.display() would display Bob’s details.

Don’t worry if this sounds confusing. You’ll be exploring objects in much more detail later in these lessons. For now, you just need to know the basics. JavaScript supports three kinds of objects:

  • Image Built-in objects—These objects are built in to the JavaScript language. You’ve already encountered one of these, Date, in Lesson 4. Other built-in objects include Array and String, which you’ll explore in Lesson 22; Math, which is also explained in Lesson 22; Boolean; Number; and RegExp.

  • Image DOM (Document Object Model) objects—These objects represent various components of the browser and the current HTML document. For example, the alert() function you used earlier in this lesson is actually a method of the window object. You’ll explore these in more detail in Lesson 21, “Working with the Document Object Model (DOM).”

  • Image Custom objects—These are objects you create yourself. For example, you could create a person object, as mentioned earlier in this section.

Conditionals

Although you can use event handlers to notify your script (and potentially the user) when something happens, you might need to check certain conditions yourself as your script runs. For example, you might want to validate on your own that a user entered a valid email address in a web form.

JavaScript supports conditional statements, which enable you to answer questions. A typical conditional uses the if statement, as in this example:

if (count == 1) {
  alert("The countdown has reached 1.");
}

This compares the variable count with the constant 1 and displays an alert message to the user if they are the same. It is quite likely you will use one or more conditional statements in most of your scripts, and therefore an entire lesson is devoted to this concept: Lesson 23, “Controlling Flow with Conditions and Loops.”

Loops

Another useful feature of JavaScript—and most other programming languages—is the capability to create loops, or groups of statements that repeat a certain number of times. For example, these statements display the same alert 10 times, greatly annoying the user:

for (i=1; i<=10; i++) {
  alert("Yes, it's yet another alert!");
}

The for statement is one of several statements JavaScript uses for loops. Computers are good at performing repetitive tasks like looping. You will use loops in many of your scripts, in much more useful ways than this example, as you’ll see in Lesson 23.

Event Handlers

As mentioned in Lesson 4, not all scripts are located within <script> tags. You can also use scripts as event handlers. Although this might sound like a complex programming term, it actually means exactly what it says: Event handlers are scripts that handle events. You learned a little bit about events in Lesson 19 but not to the extent you’ll read about them in this lesson or in Lesson 24, “Responding to Events and Using Windows.”

In real life, an event is something that happens to you. For example, the things you write on your calendar are events, such as Dentist appointment or Freds birthday. You also encounter unscheduled events in your life, such as a traffic ticket, an IRS audit, or an unexpected gift from relatives.

Whether events are scheduled or unscheduled, you probably have normal ways of handling them. Your event handlers might include things such as When Freds birthday arrives, send him a present or When relatives visit unexpectedly, turn out the lights and pretend nobody is home.

Event handlers in JavaScript are similar: They tell the browser what to do when a certain event occurs. The events JavaScript deals with aren’t as exciting as the ones you deal with; they include such events as When the mouse button is pressed and When this page is finished loading. Nevertheless, they’re a very useful part of JavaScript.

Many JavaScript events (such as mouse clicks, which you’ve seen previously) are caused by the user. Rather than doing things in a set order, your script can respond to the user’s actions. Other events don’t involve the user directly; for example, an event can be triggered when an HTML document finishes loading.

Each event handler is associated with a particular browser object, and you can specify the event handler in the tag that defines the object. For example, images and text links have an event, onmouseover, that happens when the mouse pointer moves over the object. Here is a typical HTML image tag with an event handler:

<img src="button.gif" onmouseover="highlight();">

You specify the event handler as an attribute within the HTML tag and include the JavaScript statement to handle the event within the quotation marks. This is an ideal use for functions because function names are short and to the point and can refer to a whole series of statements.

Using an event handler within HTML is fairly easy. Listing 20.1 shows an HTML document that includes a simple event handler.

Listing 20.1 An HTML Document with a Simple Event Handler

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Event Handler Example</title>
    <meta name="viewport"
          content="width=device-width, initial-scale=1">
  </head>
  <body>
    <h1>Event Handler Example</h1>
     <div>
     <a href="http://www.google.com/"
    onclick="alert('A-ha! An Event!');">Go to Google</a>
     </div>
  </body>
</html>

The event handler is defined with the following onclick attribute within the <a> tag that defines a link:

onclick="alert('Aha! An Event!');"

This event handler uses the DOM’s built-in alert method of the window object to display a message when you click on the link; after you click OK to dismiss the alert, your browser continues on to the URL. In more complex scripts, you usually define your own functions to act as event handlers. Figure 20.2 shows an example of this in action.

A screenshot of a webpage with a link reading Go to Google (which is clicked), overlapped by an alert box that reads, A-Ha! An event. The alert box has an Ok button.
Figure 20.2 The browser displays an alert when you click the link.

You’ll use other event handlers throughout these lessons, especially in Lesson 24.

Note

After you click the OK button to dismiss the alert, the browser follows the link defined in the <a> tag. Your event handler could also stop the browser from following the link, as you will learn in Lesson 24.

As mentioned in earlier lessons, using an attribute on the HTML tag is not unobtrusive. You’ll learn how to make event handlers unobtrusively in later lessons.

Which Script Runs First?

You are not limited to a single script within a web document: One or more sets of <script> tags, external JavaScript files, and any number of event handlers can be used within a single document. With all these scripts, you might wonder how the browser knows which to execute first. Fortunately, this is done in a logical fashion:

  • Image Sets of <script> tags within the <head> element of an HTML document are handled first (in the order in which they are written in the HTML), whether they include embedded code or refer to a JavaScript file. Because scripts in the <head> element will not create output in the web page, many designers use scripts placed here to define functions for use later.

  • Image Sets of <script> tags within the <body> section of the HTML document are executed after those in the <head> section, while the web page loads and displays. If there are two or more scripts, they are executed in the order in which they are written in the HTML.

  • Image Event handlers are executed when their events happen. For example, the onload event handler is executed when the body of a web page loads. Because the <head> section is loaded before any events, you can define functions there and use them in event handlers.

It’s important to know that every time the browser encounters a <script> tag, it stops concurrent downloading to download and parse just that script. All other HTML tags and elements are threaded, which means browsers can download several at a time. This is why it’s important to have as few <script> tags in your document as possible, and, whenever possible, to load them last in the HTML. Taking these steps helps ensure that everything else on the page loads before the scripts do and thus makes your pages faster.

JavaScript Syntax Rules

JavaScript is a simple language, but you do need to be careful to use its syntax—the rules that define how you use the language—correctly. The rest of these lessons cover many aspects of JavaScript syntax, and this lesson discusses a few basic rules that will help you throughout these lessons as well as when you are working on your own.

Case Sensitivity

Almost everything in JavaScript is case sensitive, which means you cannot use lowercase and capital letters interchangeably. Here are a few general rules:

  • Image JavaScript keywords, such as for and if, are always lowercase.

  • Image Built-in objects, such as Math and Date, are capitalized.

  • Image DOM object names are usually lowercase, but their methods are often a combination of uppercase and lowercase—sometimes called camel case. Usually uppercase letters are used to start all words except for the first one, as in setAttribute and getElementById.

When in doubt, follow the exact case used in these lessons or another JavaScript reference. If you use the wrong case, the browser will usually display an error message.

Variable, Object, and Function Names

When you define your own variables, objects, or functions, you can choose their names. Names can include uppercase letters, lowercase letters, numbers, and the underscore (_) character. Names must begin with a letter or an underscore.

You can choose whether to use uppercase or lowercase in your variable names, but remember that JavaScript is case sensitive, so, for example, score, Score, and SCORE would be considered three different variables. Be sure to use the same name each time you refer to a variable.

Reserved Words

One more rule applies to variable names: They must not be reserved words. These include the words that make up the JavaScript language, such as if and for, DOM object names such as window and document, and built-in object names such as Math and Date.

For a list of JavaScript reserved words, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords.

Spacing

JavaScript ignores blank space (which programmers call whitespace). You can include spaces and tabs within a line, or blank lines, without causing an error. Blank space often makes a script more readable, so do not hesitate to use it.

Using Comments

JavaScript comments enable you to include documentation within your script. Brief documentation is useful if someone else needs to understand the script, or even if you try to understand it when returning to your code after a long break. To include comments in a JavaScript program, begin a line with two slashes, as in this example:

//this is a comment.

You can also begin a comment with two slashes in the middle of a line, which is useful for documenting a script. In this case, everything on the line after the slashes is treated as a comment, which the browser ignores. For example, the following line is a valid JavaScript statement followed by a comment explaining what is going on in the code:

a = a + 1; // add 1 to the value of the variable a

JavaScript also supports C-style comments (also used in PHP), which begin with /* and end with */. These comments can extend across more than one line, as the following example demonstrates:

/* This script includes a variety
of features, including this comment. */

Because JavaScript statements within a comment are ignored, this type of comment is often used for commenting out sections of code. If you have some lines of JavaScript that you want to temporarily take out of the script while you debug it, you can add /* at the beginning of the section and */ at the end.

Caution

Because these comments are part of JavaScript syntax, they are valid only inside <script> tags or within an external JavaScript file. If you try to use them in an HTML document outside the <script> tags, the strings will be rendered by the browser.

Best Practices for JavaScript

Now that you’ve learned some of the very basic rules for writing valid JavaScript, it’s also a good idea to follow a few best practices. The following practices are not required, but you’ll save yourself and others headaches if you begin to integrate them into your development process:

  • Image Use comments liberally—Comments make your code easier for others to understand and also easier for you to understand when you edit it later. They are also useful for marking the major divisions of a script.

  • Image Use a semicolon at the end of each statement and use only one statement per line—Although you learned in this lesson that you do not have to end each statement with a semicolon (if you use a new line), using semicolons and only one statement per line will make your scripts easier to read and also easier to debug.

  • Image Use external JavaScript files whenever possible—Separating JavaScript into external files helps pages load more quickly and also encourages you to write modular scripts that can be reused.

  • Image Avoid being browser specific—As you learn more about JavaScript, you’ll learn some features that work in only one browser. Avoid such features unless absolutely necessary, and always test your code in more than one browser to ensure that everything works.

  • Image Keep JavaScript optional—Don’t use JavaScript to perform an essential function on your site (for example, for the primary navigation links). Whenever possible, users without JavaScript should be able to use your site, although it might not be quite as attractive or convenient without the JavaScript. This strategy is known as progressive enhancement.

There are many more best practices involving more advanced aspects of JavaScript. You’ll learn about them not only as you progress through the lessons but also over time as you work with JavaScript and as you collaborate with others on web development projects.

Understanding JSON

Although JSON, or JavaScript Object Notation, is not a part of the core JavaScript language, using it is in fact a common way to structure and store information either used by or created by JavaScript-based functionality on the client side. Now is a good time to familiarize yourself with JSON (pronounced “Jason”) and some of its uses.

Note

JSON formalizes the idea of encoding data in JavaScript. See www.json.org for details and code examples in many languages.

JSON-encoded data is expressed as a sequence of parameter and value pairs, with a colon separating each parameter and its value. These "parameter":"value" pairs are separated by commas:

"param1":"value1", "param2":"value2", "param3":"value3"

Finally, the whole sequence is enclosed in curly braces to form a JSON object. The following example creates a variable called yourJSONObject:

var yourJSONObject = {
   "param1":"value1",
   "param2":"value2",
   "param3":"value3"
};

JSON objects can have properties and methods accessed directly using the usual dot notation, as shown here:

alert(yourJSONObject.param1); // alerts 'value1'

More generally, though, JSON has a general-purpose syntax for exchanging data in a string format. It is easy to convert a JSON object into a string through a process known as serialization; serialized data is convenient for storage or transmission around networks.

One of the most common uses of JSON these days is as a data interchange format used by application programming interfaces (APIs) and other data feeds that are consumed by a front-end application that uses JavaScript to parse the data. This increased use of JSON in place of other data formats such as XML has come about for several reasons:

  • Image JSON is easy to read—for both people and computers.

  • Image JSON is simple in concept. A JSON object is nothing more than a series of "parameter":"value" pairs enclosed by curly braces.

  • Image JSON is largely self-documenting.

  • Image You can create and parse JSON quickly.

  • Image JSON is a subset of JavaScript, which means no special interpreters or other additional packages are necessary.

Summary

In this lesson, you learned about several components of JavaScript programming and syntax, such as functions, objects, event handlers, conditions, and loops. You also learned how to use JavaScript comments to make your script easier to read and looked at a simple example of an event handler. Finally, you were introduced to JSON, a data interchange format that is commonly used by JavaScript-based applications.

Q&A

Q. I’ve heard the term object-oriented applied to languages such as C++ and Java. If JavaScript supports objects, is it an object-oriented language?

A. Yes, although it might not fit some people’s strict definition of object-oriented. JavaScript objects do not support all the features that languages such as C++ and Java support, although the latest versions of JavaScript have added more object-oriented features.

Q. Having several scripts that execute at different times seems confusing. Why would I want to use event handlers?

A. Using event handlers is the ideal way (and, in JavaScript, the only way) to handle advanced interactions within a web page, such as using buttons, check boxes, and text fields in ways beyond simply completing a form and sending it to a recipient. Rather than write a script that sits and waits for a button to be pushed, you can create an event handler and let the browser do the waiting for you, while allowing the user to continue viewing elements and text on the page.

Workshop

The Workshop contains quiz questions and activities to help you solidify your understanding of the material covered. Try to answer all questions before looking at the “Answers” section that follows.

Quiz

1. A script that executes when the user clicks the mouse button is an example of what?

  1. An object

  2. An event handler

  3. An impossibility

  4. A method

2. Which of the following can a JavaScript function do?

  1. Accept parameters

  2. Return a value

  3. Write data to disk

  4. Both A and B

3. Which of the following is executed first by a browser?

  1. A script in the <head> section

  2. A script in the <body> section

  3. An event handler for a button

  4. A click on a link

4. How many lines make up a valid JavaScript statement?

  1. One

  2. Two

  3. Three

  4. As many as you need

5. How do you separate statements in a script?

  1. A space

  2. A newline

  3. A semicolon

  4. Both B and C

6. How would you write a statement that defines a variable called myVariable and assigns it the value 27?

  1. myVariable 27;

  2. var myVariable 27;

  3. var myVariable = 27;

  4. var myVariable == 27;

7. When would a script tied to an onmouseover attribute run?

  1. When the user clicks the element

  2. When the user taps the element on a touch device

  3. When the mouse hovers over the element

  4. When the mouse leaves the page

8. Is var Date = "today"; a valid variable statement? Why or why not?

  1. It is not valid because “today” is a string, not a date object.

  2. It is not valid because Date is a built-in object and therefore cannot be used as a variable name.

  3. It is not valid because you assign variables without any operator (=).

  4. It is a valid statement.

9. What are two ways to write JavaScript comments?

  1. Use // for single-line comments and /* */ for multi-line comments.

  2. Use ## for single-line comments and // // for multi-line comments.

  3. Use ; for single-line comments and /* */ for multi-line comments.

  4. Use // for single-line comments and && && for multi-line comments.

10. How would you write a JSON variable with two parameter/value pairs?

  1. var myObject = {
      "param1" "value1",
      "param2" "value2"
      };

  2. var myObject = (
      "param1":"value1",
      "param2":"value2"
      );

  3. var myObject = {
      "param1":"value1",
      "param2":"value2"
      };

  4. var myObject = (
      "param1" "value1",
      "param2" "value2"
      );

Note

Just a reminder for those of you reading these words in the print or e-book edition of this book: If you go to www.informit.com/register and register this book (using ISBN 9780672338083), you can receive free access to an online Web Edition that not only contains the complete text of this book but also features an interactive version of this quiz.

Answers

1. b. A script that executes when the user clicks the mouse button is an event handler.

2. d. Functions can both accept parameters and return values.

3. a. Scripts defined in the <head> section of an HTML document are executed first by the browser.

4. a. A statement is just one line of JavaScript code that performs a single action.

5. d. Statements can be separated by a newline character, but it’s better to use a semicolon to separate statements.

6. c. The statement is var myVariable = 27;.

7. c. It would run whenever the user hovers over the element with a mouse pointer.

8. b. It is not valid because Date is a built-in object and therefore cannot be used as a variable name.

9. a. You can use // for single-line comments and /* */ for multi-line comments.

10. c. You would write it like this:

var myObject = {
  "param1":"value1",
  "param2":"value2"
};

Exercises

  • Image Examine the date and time script you created in Lesson 4, looking for examples of methods and objects used there.

  • Image Add JavaScript comments to the date and time script to make it more clear what each line does. Verify that the script still runs properly.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.156.140