Introducing Javascript

Essential Concepts

What is Javascript?

A scripting language extends the function of a computer program by allowing its user to control the main program's behavior in powerful and precise ways. Scripting differs from programming in that it depends upon a host program -- in our case, a Web browser.

Generally speaking, scripts are much less complex than programs. This means you can do very impressive things in a scripting language like Javascript without having to master the enormous detail required for true programming. Thus you can stay focused on creativity and expressive purposes, yet still exercise significant command of your tools.

Javascript belongs to a family of languages called ECMAScript, named for the European Computer Manufacturers' Association, who standardized scripting languages at the turn of the century. Javascript was initially designed by Netscape Communications for its Navigator browser. As the name suggests, it bears some resemblance (very tenuous) to the programming language Java, created by Sun Microsystems. Like Java, all ECMAScript variants base their syntax on the UNIX programming language called C. Because of these family resemblances, learning Javascript or ActionScript will teach you much about the ways programmers work and think. Scripting languages may be the do-it-yourself version of industrial tools, but they'll still drive nails and cut wood, metaphorically speaking. While learning to script won't make you a programmer, you will be much better able to work with those masters -- capable of understanding the problems we all face when doing things with code.

Object Orientation, DOM, AJAX

In the early days (1996-2000), Javascript played a key role in something called Dynamic HTML (DHTML), which developed partly out of Netscape's attempts to extend the functional basis of Web publishing. Eventually DHTML was supplanted by a more ambitious concept, the Document Object Model (DOM). In this scheme, all aspects of a Web document (no longer conceived as a page) are accessible as software ojects -- constructions with properties and methods. Much of what used to be called Web scripting is now referred to as DOM scripting.

The DOM approach has in turn been extended by another architectural model, Asynchronous Javascript and XML, or AJAX. AJAX approaches tend to involve DOM scripting, as well as other code resources and services, including some residing outside the Web browser.

Both DOM scripting and AJAX draw on the basic notion of software objects, and are thus examples of object orientation, the currently dominant computer programming paradigm.

Aspects of Javascript

Deploying scripts

For our purposes, we'll assume Javascript instructions must occur within a special container like this:

This script container can be placed at various locations in the document: in the HEAD division, in-line within the BODY division (e.g., for a document.write() script), as the last element in the BODY, or even as a separate division of the document, following the close of BODY.

For our purposes, we will place script containers either in-line or as the last element of BODY. Both locations are relatively safe from error.

In both cases, we'll always place script containers within a block-level HTML element, such as DIV or P, like so:

When a script container occurs in-line, it operates almost identically to a regular page elment; that is, its functions are performed as the browser lays out the page. So the script placed in-line, below...

(Here's the script:)

Load-time and asysnchronous operations

The example above, using the simple write() method of the browser's document object, represents a Javascript operation that happens when the page loads (at load time).

Javascript can also operate asynchronously, while the page is resident in the browser's memory, and without any new communication from the originating server. This sort of operation is crucial to AJAX. The example below shows a very simple illustration of asynchronous operation: popping up an alert window to display information.

The button above belongs to a more or less standard HTML form whose action argument is set to "javascript: tryMe()". This reference indicates a Javascript function that must be defined somewhere on the present page (or be accessible to that page).

Here's the actual function (which you can also see by viewing source for this page):

Functions

As you can see, script instructions are often organized into a function. In object-oriented parlance, functions are also called methods.

The function we've seen in action above puts the greeting Hi there! into a pop-up or alert window. You could of course accomplish the very same effect simply by writing the key instruction of this method directly into a script container, thus:

However, the script above, lacking a function body, can do its job exactly once, when the page loads. It cannot operate repeatedly or asynchronously. Instructions contained within a function (or method) can be repeated at will, by invoking the function that contains them.

To invoke a function, you simply give its name, followed by a set of parentheses, thus:

Usually, the statement that invokes a function occurs within another function. For instance:

In the (rather silly) example above, the function beAlerted() does two things: it triggers the sayHey() function (or method), and also sets a Boolean variable to true, presumably to record the fact that the alert has been issued.

The example above assumes sayHey() is defined somewhere else in the present markup, or in a file linked to it.

Variables

In the example above, isAlerted is a variable. As in other scripting and programming languages, Javascript variables are virtual containers that store values. These values can be assigned, interrogated, and modified.

Unlike other scripting and programming languages, Javascript handles variables very loosely. It does not permit strict typing (a practice required in most other ECMAScript derivatives), whereby a variable is declared as a container that will hold only a certain type of data (Boolean values, numbers, strings, etc.). In Javascript, variables are flexibly typed in context of use. If you assign a true/false value to a variable, it's typed as Boolean; assigning text makes it a text or String variable.

In Javascript, you can change the type of a variable at will, as in this example:

Alas, poor z is not the String it thinks it is. This script displays the numerical value 123.75 in the alert window. Our variable changes to the Number type as soon as a number is assigned.

If you have prior experience with programming, or with stricter ECMA languages such as ActionScript, the looseness of Javascript variables may drive you partly insane. It's a bit like working in a pants-optional office. You'll need to adapt -- since Javascript DOES NOT PERMIT strict typing -- but remember to put your pants back on before you rejoin the normal world.

Assignment versus evaluation; conditions

To place a value within a variable, use the assignment operator = (a single equal sign). So the statement:

means let n equal 3 or assign the value 3 to the variable n.

Note that the meaning of the single equal sign differs from the meaning it has in mathematics or logic, where n=3 means that n is equal to 3, not that n becomes equal to 3.

This distinction may not seem especially important until we introduce conditions. A conditional statement, in scripting as well as in ordinary language, is an if/then construction. If the condition is met, then the consequence occurs. If conditions are basic building blocks of all scripts and programs.

However, when we need to determine if one thing equals another within a conditional statement, we can't use the single equal sign, since it is used to assign a value. We use a double equal sign instead:

The statement above instructs the browser to execute the beAlerted() function if the variable n contains the value 3. The statement is read, "if n is 3, then execute function beAlerted." Note the term "then" is represented by the space that follows if(n == 3). All languages derived from C use this convention.

When more than one consequence follows from a single condition, we use a slightly more complicated form of the conditional statement:

The curly braces {} indicate a compound consequence. Both statements within the braces depend on the initial condition. Note the use of the single equal sign as an assignment operator in the first line within the braces.

Suppose we want something to happen only in case two conditions are both met. In that case, we'd use a compound conditional clause like this:

The double ampersand && is a logical AND operator that chains two conditions together. You may also use a logical OR, which is represented by two vertical lines or "pipes" (||). In an OR situation the consequence occurs if either condition is met.

Finally suppose you want to specify one consequence if a condition is true and a second consequence if it is false. The If/Else condition serves this purpose:

The code in this example executes the beAlerted() function only if n has a value of 3. If n has any other value, it invokes beCool() instead.

Loops

Along with conditions, scripts and programs often depend heavily on loops. A loop tells a program to execute certain instructions a specified number of times, or under specified conditions. The most common form is the For loop. Here is an actual example of such a structure:

This loop takes the value of its index variable i five times and places that value in the current document (in an example of dynamic text generation, or in-line scripting). The HTML "<br />" is appended in order to place the values on separate lines. The result looks like this:

The syntax of the For loop in Javascript is almost exactly the same in C, PERL, Java, and ActionScript (though because of strict typing, most of these languages include a variable declaration that is omitted in Javascript).

In the initial parenthesis, three statements occur. The first sets a starting value for the index variable i. This value may be any number you like. The second statement sets a limit for the index variable. Limiting to numbers less than 6 means the loop will stop when i reaches 5. The third statement indicates how the loop is incremented. The instruction "i++" means that the variable i increases in value by 1 with each repetition of the loop. The increment may also be varied. Writing "i+=2" would cause the index to increase by 2 each time.

That's all for now!

While we've covered a fair amount of material here, this introduction only begins to scratch the surface of Javascript. We'll encounter many other instructions and control structures as we go further. In particular, we'll have something to say about native objects and random numbers; but we'll do this on a separate page.

The contents of this page should be plenty to get you started with Javascript.




University of Baltimore Logo

Last updated: 09/06/09 18:38:43
Copyright © 2009 School of Information Arts and Technologies