Chapter 2 - Stuff You Should Know: Basic Programming Concepts | WebReference

Chapter 2 - Stuff You Should Know: Basic Programming Concepts

Chapter 2

Stuff You Should Know:

Basic Programming Concepts

JavaScript is a rich and full-featured programming language, though as included in Netscape -- as well as Microsoft Internet Explorer and other products -- it has a fairly narrow application: to enhance HTML documents you view on the Web. With just a little bit of ingenuity, you can create JavaScript code that generate, from scratch, specialized pages customized for each person visiting your Web site, games, calculators, reminder calendars, a self-testing and scoring quiz game, and much, much more. In short, there is almost no limit to what you can do with JavaScript.

If you're new to programming, or need a refresher course, be sure to read this chapter. It details some of the key concepts you will need on your way to becoming a JavaScript expert. This chapter explains the basic concepts of programming, such as flow control, conditional testing, variables, expressions, and other topics.

Thinking Like a Nerd...,er...,Programmer

Although you don't need any previous training or experience at computer programming to master JavaScript, you will find that it does help. At the very least, you should learn how to "think like a programmer" or at least think in terms of programming and problem solving. Of course, this does not mean that you must become a programmer. You can master JavaScript and not take up programming as a new career. If you already consider yourself a programmer, then JavaScript will be a fun learning experience for you.

It is not the intent of this book to teach programming principles; that would require far too many pages. However, you can gain a good grasp of programming fundamentals by concentrating on the 11 main areas of JavaScript program design:

The Object Is the Game

As with many modern computer languages these days, JavaScript is designed around the object, which is sort of like a virtual "black box" machine. You can think of an object as a Creepy Crawlers Machine for computer programs. You put in raw ingredients (the "creepy"), put 'em in the machine, and out comes the finished crawler. The idea here is that such machines as the Creepy Crawlers are designed to accept only certain kinds of ingredients, and output certain kinds of items. One machine in your house may be designed to pump out rubber toys, another may be made to produce the perfect waffle, and a third might be only good for making julienne fries.

JavaScript objects are designed with specific tasks in mind. One object might represent the current document, another the entire window, and yet another a form within that document. Objects impose a strict compliance; you can't just manipulate any object in any way you like. This is a departure to many older programming languages, such as C or Basic, where you had complete freedom to manipulate the data in your programs in any way you wished. This freedom also comes with a price: it's rather easy to shoot yourself in the foot by making a relatively minor programming error. Objects are supposed to make programming safer, and more streamlined.

With few exceptions, everything you do in JavaScript revolves around the object. Because of this, JavaScript uses its own object-related jargon. Here are the most important terms to learn:

Read more about objects in these chapters:

Going with the Flow

The flow is the order of events your program takes to complete its task. That flow can be dictated by a strict progression from start to finish that never varies between uses. Or it can deviate depending on user input or some other condition. Flow is something you have to visualize or your programs may become hopelessly confusing in your own mind. You'll lose track of what they are supposed to do, and when.

Simple, one-function scripts can be created without a blueprint or flow chart, but you should still give extra thought and consideration to what your program is supposed to do. As you gain experience writing JavaScript programs you'll do this subconsciously. But at first you'll have to force yourself to think in terms of progression.

You will especially want to consider flow if the programs is complex in nature. You may find it helpful to draw a programming flow chart that includes the basic steps of the script, like that in Figure 2-1. Each box contains a complete step; arrows connect the boxes to indicate the progress of steps throughout the script.

<Figure 2-1. A flow chart helps you to visualize the construction of your JavaScript program.>

Flow charts are particularly handy when creating scripts that involve other scripts as part of a complex interaction using frames. For example, the JavaScript in one frame can control what happens in another frame. By making a "map" of the JavaScript program and how it interacts with everything you can better visualize the requirements and design principles involved.

Read more about flow control in these chapters:

The Benefit of Routines

One of the first things a programmer does when he or she starts on a project is to map out the individual segments, or routines, that make up the software. Even the longest, most complex program -- and this includes JavaScript programs -- consists of little more than bite-size routines. The script progresses from one routine to the next in an orderly and logical fashion.

What is a routine? A routine is any self-contained segment of code that performs a basic action. In the context of a JavaScript program, a routine can be a single command or character of text, or it can take up the bulk of a mammoth 200K HTML document (though this is obviously an extreme). Suppose your script formats text and graphics on a page, and also displays a list from which the user makes a selection. Once a selection is made, the script clears the screen and displays the result. The script can be divided into three distinct routines:

While there's no need to separate these routines within a script physically but it helps to think of the script as being composed of these more basic parts. If the script doesn't work properly, you can more easily analyze the problem if you can narrow it down to a specific segment of the code. For example, if the script is not responding to the user's choice in the list, but is formatting the screen with the proper text and graphics, then you can reasonably narrow the problem to the number 2 routine.

Many scripts simply start at the beginning and advance one step at a time to the end, taking each instruction in turn and acting upon it. This is the approach taken by the example script just cited. But better program design calls for segmenting the routines into something called functions. That way, the functions can be used in any order, and even repeated. For example, your script could easily be revised to repeat Routine 1 (formatting the document), after the user has successfully picked and item from the list and the response shown on the screen. Here's another benefit of working with discrete routines. Because the code for a particular task is all contained in a routine, it can more easily be transported to other scripts. This lets you share code so you don't have to write everything from scratch. This is the technique used in Chapter 13, "Plug and Play Routines." This chapter contains dozens of ready-to-use routines that you can drop into your JavaScript programs.

JavaScript doesn't use line numbers, as found in some other programming languages, such as Basic. Rather, you identify routines by function name. You merely provide the name of the function (routine) you want JavaScript to execute, and it executes that routine. This makes it extremely easy to revise your program, as you don't need to worry about changing line numbers as you add and remove contents.

Read more about routines in these chapters:


A variable is a special holding area for information. JavaScript uses named variables, and the names can be most any length. You make up the name of the variable as you write the script. The contents of the variable is specified by one of the following:

The information in the variable is kept so that it can be used elsewhere in the script (see Figure 2-2). This information can take many forms, and includes numbers and text. When the page is unloaded from the browser the variable is lost.

<Figure 2-2. Variables store information for later retrieval in a JavaScript program.>

JavaScript following a variable paradigm known as "loose typing." This essentially means that the contents of variables are not tightly controlled. Unlike many other languages, such as C and the older versions of Basic, you can put a text value into a variable, then replace it with a number value. JavaScript will cope by automatically figuring out what kind of data is being stored, and adjust its internal memory handling requirements to suit. In JavaScript you do not need to "declare" a variable type, such as

int MyInteger;

to define a variable named MyInteger that will contain an integer (whole number) value. In addition, you can often mix and match numbers and text without bothering to convert them to the proper data format first. This makes programming in JavaScript much easier, and cuts down on potential mistakes.

Read more about variables in these chapters:


An expression is a process a JavaScript program must follow to complete a task you've given it. Sometimes the expression is a simple math problem: "Take the contents of this variable and apply it to that value." Often times, the expression is a little more complex, like "Take this number from this variable, add 15 to it, and compare it to the value in this other variable."

When you ask a JavaScript program to perform some type of calculation or thinking process, you're asking it to evaluate an expression. For example, if the expression reads "1+1," then the script must first evaluate it (add one and one to make two) before proceeding.

Some more advanced JavaScript expressions may appear exotic, but you'll have plenty of chance to use them. The most common is evaluating if a statement is true or false. Here's a good example of a true/false expression that must be evaluated by the script:

if Number equals10, then alert ("the number is ten");

In reading the expression (which is not in acceptable JavaScript notation, but it's close), it reads "if the contents of the Number variable is equal to 10, then display a message." Before proceeding with the remainder of the program, JavaScript must pause, take a peek inside the Number variable, and apply it to the logical expression. If the result is true, then the script displays a message that reads, "the number is ten. If it's false (the Number variable has a number other than 10), then something else happens.

Read more about expressions in these chapters:


A common term in programming circles is the string. A string is simply a sequence of alphabetic or numeric characters, as shown in Figure 2-3. These characters are stored within the computer's memory one right after the other, like beads on a string. Therein lies the root of the word string.

<Figure 2-3. Strings are composed of one or more characters -- which can be letters, numbers, or symbols -- strung one after the other.>

In the context of JavaScript and other programming languages, strings are most used in variables. Once stored in a variable, the string can be acted upon by the program. For example, if the string is text, you can compare it with another string to see if the two are the same. The concept of comparing string comes in handy when designing interactive scripts. The advanced scripts throughout this book rely heavily on comparing strings.

Strings are also used to display messages to the user, and display text in the browser. For instance, you use a string to display a paragraph of text generated by JavaScript. Strings are especially important in JavaScript because an HTML document is nothing but text. This includes images, sounds, Java applets, plug-ins, and more -- all of these elements are stored in an HTML document as textual tags.

Read more about strings in these chapters:

Numeric Values

Computers are designed from the ground up to work with numeric values (numbers). The size of the number is inconsequential and is entirely up to the application running on the computer. In fact, JavaScript programs can deal with numbers as large as 1e+308 -- that's 1 with over 300 zeros after it! Unless you're having an argument with Carl Sagan over the number of stars in the known universe, you'll probably never have a reason to use a number that large. (However, such numbers are handy when dealing with high-precision decimal values. JavaScript can work with numbers with an accuracy of up to 15 digits to the right of the decimal point). As with strings (see above), numerical values are most often used in variables.

Numbers differ from strings in one important area: the computer can perform math calculations on two numbers, and provide you with the result. Calculations are not possible with strings, because you can't multiple or divide strings.

Note that JavaScript programs can store digits as numbers or as strings. It can sometimes be difficult to tell when a "number" (like 1 or 263) is a numeric value, and when it's a string. For the sake of clarity, we'll refer to numbers stored as digits in the computer's memory as a numeric value. And we'll refer to numbers stored as text characters as a number string. This is by no means standard notation in programming books, but it works for our needs.

Read more about numeric values in these chapters:

Conditional Statements

Scripts can be constructed so that they perform certain routines in one instance, and other routines in another. The script responds to specific conditions, set either by the user, by the browser, by information from the server, or by some other source.

A conditional statement is a fork in the road with a choice of two directions to take, depending on the response to a simple true/false question. JavaScript programs provide many ways to create conditional statements, but they all have one thing in common: to activate a certain routine (or group of routines) depending on external data.

Here's an example of a conditional statement. "If it's cold outside, I'll wear my jacket. Otherwise, I'll leave the jacket at home." The statement can be broken down into three segments:

Obviously, this isn't the kind of conditional statement you'll write with JavaScript. But you may design a conditional statement, for instance, that loads one document depending on one type of user input, or another document depending on other types of user input.

All conditional statements have a condition that must be met, and a specified action if the condition is true or false -- there is no other possible outcome. Not all conditional statements specify an action for both a true and a false, but most do.

Spend some time learning all the ropes of conditional statements, because this is the element of programming that gives JavaScript true intelligence. While your JavaScript programs may never have a life of their own -- though you may sometimes think they do! -- conditional statements endow them with limited smarts to perform the action you want.

Read more about conditional statements in these chapters:


A loop is a command or routine that repeats two or more times. A typical loop used in some programming languages is a "keyboard scan" where the program checks the keys you press. If you press the key the loop routine is looking for, the program breaks out of the loop (usually just momentarily) and continues on with some other routines. If the key isn't the one that the loop is looking for, the routine is restarted again.

Keyboard scans are not possible with JavaScript, as JavaScript is engineered to interact with the browser, not the computer running it. In the realm of JavaScript, you might construct a routine that insists the user respond to a prompt by providing valid data. The loop is repeated until valid data is entered.

In many ways loops are really specialized versions of conditional statements. Instead of stopping to provide a choice of two directions, the script is designed to continue the loop until a certain condition, which may be internal or external, is met. JavaScript programs contain many sophisticated ways to construct loops, including the for loop and the while loop -- both of which will be familiar to you if you've done any programming. You'll find loops helpful in tackling the most demanding JavaScript assignments.

Read more about looping in these chapters:

Entering Data

The basic JavaScript program is merely a series of commands. But you can also program scripts to stop and wait for user input. Once the user has entered the data, the script uses the information -- be it text, a number, a some other value -- to complete its task.

For example, you might have your script prompt the user for her real name or e-mail name, or some other variable information. Your script may then use that information to create a personalized page. Input data can be entered directly into the document, or can be temporarily stored in a variable. The script can then extract the contents of the variable and use it in a conditional statement, a branch, or a loop -- or even save it for use later on.

For JavaScript user input takes two forms: via an HTML form, where you enter text or make a selection, or respond to one of JavaScript's pop-up message boxes (there's one for a "confirmation" message, and a "prompt" message that asks for text input, the latter shown in Figure 2-4). For security reasons JavaScript does not allow you any other data input access.

<Figure 2-4. Message boxes prompt for user input.>

Read more about inputting date in these chapters:

Outputting Data

For reasons of security JavaScript is restricted to displaying text and graphics in the browser's main window, and also in messages boxes (in addition, JavaScript can be used to store certain kinds of restricted information in a special file on the user's computer). This display is how JavaScript outputs data for the user. If you're used to other programming environments like C or Basic, you'll find this somewhat restrictive, because you can't always make the text and graphics appear the way you want. While this can be viewed as a limitation, it's also a challenge, as it requires you to think in terms of presenting data compatible with the "host operating system," which in this case is not Windows, the Macintosh, or Unix, but Netscape.

The appearance of this data is completely up to your unique JavaScript program. You can display plain text, or add special formatting and imaging, as desired. Any Web document you can create using HTML commands you can duplicate with JavaScript.

Read more about outputting date in these chapters:

Other JavaScript Topics of Interest

You've learned about the main tools in the programmer's toolbox. There are a few additional buzzwords and topics that will help you as discover the JavaScript programming language. These are:


Syntax is the way a programming language is written. Computers are relatively stupid, and you can't as yet type a program in English or some other human language, and expect the computer to understand what you want. Rather, you must instruct the computer using code words, and format those code words in a way that it can sift through the program and determine what exactly you want to do. If you fail to format your program using the proper syntax, JavaScript will display an error message. This error message will continue until the syntax is correct, and JavaScript can understand your intentions.

JavaScript has a fairly simple syntax, modeled after the syntax used in the C programming language. While the syntax is simple, it's not always obvious. JavaScript uses parentheses, braces (the { and} characters), commas, semi-colons, periods, and other symbols to mean special things. You must study the use of these symbols and how they are used in order to master JavaScript's syntax.

Syntax is discussed in-depth in Chapter 3, "Overview of JavaScript Programming."

Parameters and Arguments

A parameter is data you supply to a JavaScript object, method, or function.. Think of parameters as digits in a phone number. In order to connect with anyone, you must provide at least seven numbers (for a phone number in the US). Leave out a number and the call isn't complete. Parameters in JavaScript are much the same. The parameters tell JavaScript what you want to do with the object, method, or function. Not all objects, methods, and functions use parameters, but many do.

Closely aligned to the parameter is the argument. In fact, some programmers consider parameters and arguments to be the same thing, but I make the distinction for the sake of simplicity. The difference:

Entities and Instructions

Because of JavaScript's use of objects, talking about the language can get redundant. For completeness you have to say things like "A parameter is data you supply to a JavaScript object, method, or function." Obviously repeating "object, method, or function" each time can get tiresome. Instead, the word entities is used (in this book at least) to generically refer to JavaScript objects, methods, properties, functions, and events.

An instruction is like a generic term for one or more "commands" given to JavaScript to execute. In other programming languages the instruction might go by the name of "command" or "command line."


JavaScript programs are designed to be read by a machine -- or more accurately, Netscape (or other browser) running on a machine. What these programs do aren't always obvious to humans, so most programmers add comments to their work for the benefit of themselves and for others. The comments explain -- usually briefly -- what a given JavaScript instruction does. The comment is marked off using special syntax: the // double slash characters is the most commonly used. Comments can also be used to include copyright and distribution in the script.

The HTML markup language also supports comments, but the syntax is different from that used in JavaScript. As used in Netscape, a comment in HTML markup begins with the character sequence <!-- and ends with the sequence -->.

Comments are welcome

Copyright © 1996 Gordon McComb and
Revised: October 26, 1996