Home > Articles

Getting Started with JavaScript Programming

  • Print
  • + Share This
This chapter is from the book What You'll Learn in This Hour:

Organizing scripts using functions

What objects are and how JavaScript uses them

How JavaScript can respond to events

An introduction to conditional statements and loops

How browsers execute scripts in the proper order

Syntax rules for avoiding JavaScript errors

Adding comments to document your JavaScript code

You've reached the halfway point of Part I of this book. In the first couple of hours, you've learned what JavaScript is, learned the variety of things JavaScript can do, and created a simple script.

In this hour, you'll learn a few basic concepts and script components that you'll use in just about every script you write. This will prepare you for the remaining hours of this book, in which you'll explore specific JavaScript functions and features.

Basic Concepts

There are a few basic concepts and terms you'll run into throughout this book. 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 three statements are from the date and time example in Hour 2, "Creating Simple Scripts":

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

Although a statement is typically a single line of JavaScript, this is not a rule—it's possible 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. You can also omit the semicolon if you start a new line after the statement. If you combine statements into a single line, you must use semicolons to separate them.

Combining Tasks with Functions

In the basic scripts you've examined so far, you've seen some JavaScript statements that have a section in parentheses, like this:

document.write("Testing.");

This is an example of a function. Functions provide a simple way to handle a task, such as adding output to a web page. JavaScript includes a wide variety of built-in functions, which you will learn about throughout this book. A statement that uses a function, as in the preceding example, is referred to as a function call.

Functions take parameters (the expression inside the parentheses) to tell them what to do. Additionally, 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.")

You can also create your own functions. This 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

In Hour 2, you learned that variables are containers 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 them in Hour 5, "Using 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.

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

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. These are functions that work with the 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 this book. For now, you just need to know the basics. JavaScript supports three kinds of objects:

  • Built-in objects are built in to the JavaScript language. You've already encountered one of these, Date, in Hour 2. Other built-in objects include Array and String, which you'll explore in Hour 5, and Math, which is explained in Hour 8, "Using Built-in Functions and Libraries."
  • DOM (Document Object Model) objects represent various components of the browser and the current HTML document. For example, the alert() function you used earlier in this hour is actually a method of the window object. You'll explore these in more detail in Hour 4.
  • Custom objects are objects you create yourself. For example, you could create a person object, as in the examples in this section. You'll learn to use custom objects in Hour 6.

Conditionals

Although event handlers notify your script when something happens, you might want to check certain conditions yourself. For example, did the user enter a valid email address?

JavaScript supports conditional statements, which enable you to answer questions like this. 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. You will use conditional statements like this in most of your scripts.

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. This is the sort of thing computers are supposed to be good at: performing repetitive tasks. You will use loops in many of your scripts, in much more useful ways than this example.

Event Handlers

As mentioned in Hour 1, "Understanding JavaScript," 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.

In real life, an event is something that happens to you. For example, the things you write on your calendar are events: "Dentist appointment" or "Fred's birthday." You also encounter unscheduled events in your life: for example, a traffic ticket, an IRS audit, or an unexpected visit 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 Fred's 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 clicks and When this page is finished loading. Nevertheless, they're a very useful part of JavaScript.

Many JavaScript events (such as mouse clicks) 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 is 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 to 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.

See the Try It Yourself section at the end of this hour for a complete example of an event handler within an HTML document.

Which Script Runs First?

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

  • Sets of <script> tags within the <head> section of an HTML document are handled first, whether they include embedded code or refer to a JavaScript file. Because these scripts cannot create output in the web page, it's a good place to define functions for use later.
  • 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 is more than one script in the body, they are executed in order.
  • 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.
  • + Share This
  • 🔖 Save To Your Account