Contact Forked Web Tools
 Password Troubles?
 Advertise On FWT
User Name  Password 
Knowledge Center 
Home Page Software Center Knowledge Center Control Panel
50+ Programming Examples
Learn The Basics Of Web Programming
HTML
Reference
&
Tutorial
CSS
Reference
&
Tutorial
DOM
Reference
&
Tutorial
JavaScript
Reference
&
Tutorial
JavaScript
This document takes 25 to 35 minutes to read
What is JavaScript?

JavaScript is the workhorse of the common Internet page. It is used to carry out the higher, more advanced functions inherent to more and more of today's web pages. With it you can interact with the user input for an HTML FORM control, for instance. There are many visual effects you can accomplish using JavaScript such as flying banners, fades, and other effects. Your skill level and creativity are the only limits to what you can accomplish. We'll give you the skills; you have to provide the imagination.

After the creation and widespread acceptance of the Internet, the makers of the standards we use today realized that there was a huge hole in the capabilities of the online web browser. CGI (Common Gateway Interface) scripting had become the practice for processing user input, but it took its toll on the servers used to process the commands, raising the cost of doing business. This cost was addressed and partly solved with the creation of JavaScript, which was first intended to relieve server load by processing some of the common user input into a form the server could use. Some examples are verification and validation of user input. Verifying a five digit zip code or six digit postal code are very common applications of JavaScript. The server load was therefore reduced by executing some of the code - that was previously in the CGI script on the server - on the user's machine.

JavaScript is Object Oriented, meaning that you create an object with a certain set of properties that does a certain thing. You then re-use it as many times as you have a need for. This object oriented architecture is what all new and semi-new languages are migrating to - it solves many of the problems of the older "inline" languages which start processing from the top and work down the list of commands. These inline languages are slow and tedious, and are of limited capability. Object Oriented languages solved the problems inherent to this form of programming by making its objects available to the rest of the script.

The modular programming style of the Object Oriented approach involves keeping about three different rules in mind. Take a look.

Create your object with an eye toward re-using it later.
Identify common, repetitive tasks and make the object to do them.
These identified common tasks, now objects, are placed in external library files of .js extensions.

Placing the re-usable code in an external file makes it available to the rest of your site content through the use of an HTML LINK element. This is advanelementeous because you need only change the contents of one file to make a change or revision. The alternative is to place the script in every file, creating the need to make changes or revisions in every single file on your web site that uses the code. You can see the advanelementes of this approach, which was inspired by the CSS external style sheet.

Another great advanelemente of JavaScript is its platform independence - it can run on almost any machine created because its specifications don't change from platform to platform. There are some inherent inconsistencies, but as a whole the language is interpreted in much the same way. Keep in mind that errors by programmers create a huge array of some very strange inconsistencies on each platform. Some can be used in an advanelementeous way, while others severely limit the capabilities of certain objects.
JavaScript Security

In your evolution as a web developer, you'll run into some security problems eventually. The makers of JavaScript have identified and solved most of the really glaring security holes, while the browser vendors have plugged up some the holes themselves, along with adding a certain measure of guaranteed security through browser operations. There are several different approaches to security inherent in JavaScript. Each has its own pros and cons, but as a whole they work pretty good. Some of the security procedures are within the JavaScript interpreter, and some are within the browser itself. As you begin to develop, you (or your employer) will no doubt insist on the implementation of some measure of security. Not taking security considerations into account will lead to tampering. It's a fact, so you have to deal with it. Leaving out security in your development will open your creation (and your company) to tampering. Your site users will not use your offered content when word gets out that they are vulnerable due to your security holes.

The browser runs off of the operating system itself, which means that the file system of the user's machine is a potential target for malicious users. It is entirely possible to access a user's directory listing through JavaScript. Hackers know this, and exploit it on a regular basis. Security starts with your servers, since it is there that the user downloads - and executes upon their machine - your code. Your servers must be tightly controlled and regularly monitored. Your code must be clean, leaving no threads open to outside access. This is the developerís responsibility. More about threads in a later section.

User responsibilities are basically whether or not to trust your content to run in their machines, leading us back to the security you, the developer, will implement. This ability to trust your content and run or not run your scripts is within the capabilities of the browser - it is a setting in the preferences section of the browser.

JavaScript Syntax and Rules

There are a few key things you need to know about JavaScript syntax, as well as the general rules of conduct for creating effective and efficient (not to mention funcitonal) scripts. This document outlines the basic concepts JavaScript requires for functionality as well as well formedness. The rules and syntax are generally very easy to understand - this is what makes JavaScript so popular and powerful. You'll see that most of JavaScript is very intuitive once you know the basics. You'll be up and scripting in no time.

The <SCRIPT> Element

All JavaScript statements and functions must be enclosed within the opening and closing HTML <SCRIPT> element. The LANGUAGE attribute is optional, and if left out the browser will assume you wish to use the most recent version of the JavaScript specifications. Examine the below example of a SCRIPT element to be used within a document.

<SCRIPT LANGUAGE="JavaScript" SRC="script.js"></SCRIPT>

The example shows an external JavaScript library, defined with the SRC attribute, called "script.js". You may call your external JavaScript file by any name you choose with the norm being for something descriptive. An external JavaScript library is any file of the ".js" extension that contains the script you wish to execute within your page. Choosing to place your script within an external file is entirely up to you. The script will work the same if you don't use an external library and wish to place your code within the HTML document. If you choose to place the script within your document, follow the below example.

<SCRIPT LANGUAGE="JavaScript">
<! --

- - - Insert your code here - - -

-- >
</SCRIPT>


You can see that the use of the SCRIPT element is fairly easy and to the point - there are no real shortcomings or hidden functionality. Everything is very intuitive. Notice also that the code is nested within the opening and closing comment element (). This is to provide for older browsers that don't understand JavaScript, or for browsers with the JavaScript capability turned off. Leaving out the comment element in this situation would write your code to the browser window, making it look very messy and certainly not the way you intended. There is yet another combination which is shown below.

<SCRIPT LANGUAGE="JavaScript" SRC="script.js">
<! --

- - - Insert your code here - - -

-- >
</SCRIPT>


In this example, the external library is used, as well as some code within the opening and closing SCRIPT element. You would normally use this when you have a scripting need that is specific to that page, but which requires some of the code contained within the library. This why the .js file is called a library - it contains the objects, variables, and statements that can be re-used throughout your entire web site. This is a good example of the Object Oriented direction that JavaScript is taking. The advanelementes are widespread and very obvious.

Most of the time, you would place your opening and closing SCRIPT element within the HEAD of your document, though this rule isn't concrete - your SCRIPT element can appear anywhere within the HTML document. You may nest the SCRIPT element within other element just as you would a normal element. The SCRIPT element absolutely requires the closing (</SCRIPT>) element, or the script will assume the rest of your page (including HTML, CSS, and DOM statements) is part of the script. Your script just won't work under those conditions.
The Semi - Colon

JavaScript uses the semi-colon extensively. It is used to terminate a line of code within a function or a variable anywhere within the SCRIPT element. It tells the JavaScript parser and engine that the code on the first line should be executed before executing the next line. While it isn't necessary for absolutely every line, it is a good programming convention to terminate every statement and variable with a semi-colon. This takes the guesswork out of executing your script. A semi-colon after every statement and variable will ensure that the JavaScript parser doesn't read your code wrong.

Because JavaScript is considered to be a "loosely typed" language, leaving out a semi-colon will not throw an error. It is this loosely typed functionality that is a great selling point for JavaScript. Languages like C+ require absolutely every line to be terminated with a semi-colon. This strict adherence to a syntactical convention is what makes working with the "higher languages" so annoying. Examine the below example of a simple "Hello World" function, written in JavaScript, which utilizes the semi-colons in the proper places.

<SCRIPT LANGUAGE="JavaScript">
<! --

function writeToScreen() {
document.write("Hello World !!!");
}

-- >
</SCRIPT>


This is obviously an incredibly simple example, but it shows the correct placement of the semi-colon. Adhere to these simple rules, and you'll have no problems in your future scripting endeavors.

Comment Statements

You've seen one use of the comment element in the above SCRIPT element examples. The "<! -- and -- >" element are comment element used to tell the browser not to write the textual content within to the browser window. There are three types of comment, and each is used a bit differently, as shown below.

<! -- and -- > - This type comment statement can only be used within the opening and closing SCRIPT element, and may comment out more than one line of content.
/* and */ (Block of Comments) - The "Block of Comments" tells the browser to disregard the rendering of the content within the opening and closing element. The content may span more than one line.
// (Single Line Comment) - The "Single Line Comment" tells the browser to disregard the rendering of the content within the opening and closing element. The content may not span more than one line.

Keeping these simple rules in mind when beginning your JavaScript code will not only speed things up (less errors), but also make your code easy to read and understand at a later time.

Data Types - Number

There are a number of different types of data that JavaScript can work with. The different types of data are Numbers, Strings, Boolean, null, and undefined. Each is used in a slightly different way for varying functionality. Understanding each data type is of paramount importance when you begin to write more complex scripts that require the use of more than one type of data.

In JavaScript, every number data type is treated as a floating-point number. A floating-point number is a number that includes a decimal place. For example, the fraction one-half wouldn't be written as .5, but as 0.5. Multiply that 0.5 by 6.1234 (or any number, really), and the decimal (the "point") will have "floated" to a new position within the new number. Hence the term "Floating Point". Because of this floating-point capability, JavaScript is great to use with numbers. Combine this with its loosely typed nature and you get a very easy to use and flexible yet powerful programming language.

Within the Numbers data type, there are a few different variations that must be addressed. Understanding these variations is crucial to your skill in working with them. As with most concepts within JavaScript, they are easy to understand. Along with the different number types are several built in number values that can be used within your scripts. The different types and built in values are as follows.

Integers

An integer is a number that exists without a decimal place. It is a whole number. For example, the number 5 would be an integer, but the number 5.5 would not be due to the existence of a decimal place. An integer may be positive or negative. An integer may be stated as a decimal, octal, or hexadecimal number. The below list explains what is meant by the terms decimal, octal, and hexadecimal.

Decimal - A decimal number is any number that exists with a base number of 10. The decimal number is what we (humans) use in every day numbering. It is represented by the numbers (or combinations of) 0 to 9.
Hexadecimal - A Hexadecimal number is a number that exists with a base number of 16. The hexadecimal numbering system is widely used within the computing industry because a large value may be stated using a small amount of numbers. It is represented by the numbers 0 to 9 (which represent the decimal numbers 0 to 9) and the letters A to F (which represent the decimal numbers 10 to 15). A hexadecimal number must begin with 0x or 0X when stated within JavaScript. An example of a hexadecimal number stated within JavaScript is 0XFF that represents the decimal number 255.
Octal - An Octal number is a number that exists with a base number of 8. The Octal numbering system isn't used within the computer industry as much as the hexadecimal numbering system, but it still finds some applications. It is represented by the numbers 0 to 7 and is stated within JavaScript with a zero following the actual number value. For example, the number 6 in octal must be stated as 06. An example of an octal number stated within JavaScript is 077 that represents the decimal number 63.

You'll get a feel for thinking in these differing number systems with some practice. Don't feel discouraged if you don't catch on quickly. Thinking in a number system other than ten is extremely difficult for a human.

Floating Point Numbers

As explained earlier, a floating-point number is a number that contains a decimal. A Floating-point number may also be expressed through the means of exponential notation. An exponential number may be expressed with the base number followed by an e or E, followed by the power you wish to raise the number to. For example, the number 8 may be expressed as the decimal number 2 raised to the third power as such: 2E3.
Built In Values

There are a number of different built in values you may have a use for. Use these values with the Math object to achieve your desired result. You'll learn more about the Math object later, for now what is important now is that you know they exist. The different built in values are as follows.

Math.E - This represents the base of natural logarithms, also called Euler's Constant, which is 2.718281828459045 as a decimal floating point number.
Math.LN2 - This represents the value for the natural logarithm of 2, which is 0.6931471805599453 as a decimal floating-point number.
Math.LN10 - This represents the value for the natural logarithm of 10, which is 2.302585092994046 as a decimal floating point number.
Math.LOG2E - This represents the value for the base 2 of the log of E. E represents Euler's Constant, which is 2.718281828459045 as a decimal floating point number.
Math.LOG10E - This represents the value for the base 2 of the log of E. E represents Euler's Constant, which is 2.718281828459045 as a decimal floating point number.
Math.PI - This represents the value of PI, which is 3.141592653589793 as a decimal floating point number.
Math.SQRT2 - This represents the square root of 2, which is 1.4142135623730951 as a decimal floating-point number.
Math.SQRT1_2 - This represents the square root of one half, which is 0.7071067811865476 as a decimal floating-point number.

You may use the above Math functions alone or together within your JavaScript functions. For a more detailed look at each of the above Math object properties, see the JavaScript Language Reference, Object Properties.

Special Values

JavaScript has provided five different properties of the Number object to further its capabilities as a math intensive language. They are quite common in the world of mathematics, but not so common in the world of programming. They are as follows.

Number.MAX_VALUE - This property is used to return the largest number possible available to JavaScript. This number is 1.7976931348623157e+308.
Number.MIN_VALUE - This property is used to return the smallest number possible available to JavaScript. This number is 5e-324, which is five to the negative 324, which is 5 with 324 zeros in front of it, then a decimal point.
Number.NaN - This property is used to signify that the value is NaN, which stands for Not A Number. It simply has no other value but NaN. It is equal to no other number, including itself.
Number.POSITIVE_INFINITY - The POSITIVE_INFINITY property is returned when a calculation returns a number greater than the largest Positive number available to JavaScript, which is 1.7976931348623157e+308.
Number.NEGATIVE_INFINITY - The NEGATIVE_INFINITY property is returned when a calculation returns a negative number greater than the largest negative number available to JavaScript, which is 5e-324.

You may use the above Number functions alone or together within your JavaScript functions. For a more detailed look at each of the above Number object properties, see the JavaScript Language Reference, Object Properties.

Data Types - String

There are a number of different types of data that JavaScript can work with. The different types of data are Numbers, Strings, Boolean, null, and undefined. Each is used in a slightly different way for varying functionality. Understanding each data type is of paramount importance when you begin to write more complex scripts that require the use of more than one type of data.

A String is basically a textual string of letters or an alphanumeric string of letters and numbers. Also included are special characters such as the copyright (©) character and punctuation marks. All of the characters used within the string must conform to the ISO-Latin-1 character set. Of all of the data types, the string data type is used most often. The String data type is defined by placing the string within quotes, such as "This is a string of text". You may place single quotes within double quotes. If you require double quotes within the string, use single quotes to encapsulate the string, such as 'This is the "string" of text'. If at any time you require double quotes to be present within double quotes, you will have to use what are called escape characters. The escape character for a double quote is \" - fairly easy to remember. A full list of escape characters used within JavaScript is given below.

\b - Represents a backspace - the pressing of the "backspace" key.
\f - Represents a form feed, which is a function of your printer.
\n - Represents a new line. The characters following will be placed on a new line.
\r - Represents a carriage return - the pressing of the "enter" key.
\t - Represents a tab space - the pressing of the "tab" key.
\' - Represents a single quote.
\" - Represents a double quote.
\\ - Represents a backslash.
\XXX - Represents a character represented by three digits in the octal numbering system to a maximum of 377 octal.
\XX - Represents a character represented by two digits in the hexadecimal numbering system to a maximum of FF hexadecimal.
\uXXXX - Represents a Unicode character represented by four hexadecimal digits.

Using the above escape characters, examine the following.

var textString = new String("The word \"this\" is in double quotes");

The above example utilizes the double quote escape character to illustrate how it is use within a string. The above example, when written to your browser screen, will look as follows.

The word "this" is in double quotes

You should have an idea of how the escape characters are used now. That's it for the String data type.

Data Types - Other Types

There are a number of different types of data that JavaScript can work with. The different types of data are Numbers, Strings, Boolean, null, and undefined. Each is used in a slightly different ways for varying functionality. Understanding each data type is of paramount importance when you begin to write more complex scripts that require the use of more than one type of data.

Within the computing worlds, you will encounter many instances where a data type of Number or String just will not do. JavaScript has provided for this with three types of data that fill in the rest of the needs of todayís programmer. These data types are Boolean, null, and undefined. Each is looked at in depth in the following sections.
Boolean

Simply put, a Boolean data type is a piece of data that is either "true" or "false". It has only these two values for you to work with, but with it you can do some pretty interesting things. It is something like a bridge between the returned values of some objects and the output or action you wish to perform via your script. It is sometimes easier to think of the Boolean true as "yes" and the Boolean false as "no". Some JavaScript objects will also see the Boolean true (yes) as the number 1 and the Boolean false (no) as the number 0 (zero).

null

The null data type is the data type returned from a JavaScript operation when the operation has no value. null and 0 (zero) are not considered to be the same, which is a common error because other languages treat null and zero as the same value. Keep it in mind: null and zero are two completely different values in JavaScript.

undefined

The undefined data type is not in any way equal to the null data type. It represents a situation where the script knows what type of data should be present, although there is no data present to be returned. When working with numbers, the undefined data type is equal to NaN (which is not equal to anything, including itself). When working with strings, the undefined data type is equal to undefined (and nothing else). When working with Boolean values, the undefined data type is equal to the Boolean false.

Variables

A variable can be defined as a temporary container for a changing piece of information. This information can be of any data type, size, or value within the limits of JavaScript, including no data at all - it may simply exist. A variable may contain any of the many JavaScript Object, Methods, Properties, Arrays or values. Variables may be used within functions and statements, of which there are two broadly defined types.

The Scope of a Variable - Local Variable vs. Global Variable

A variable can be said to be a Local Variable if it is defined within the space contained by a function. That is, it must be declared within the opening and closing braces that enclose the function, thus becoming part of that one function. It is not available to any other function but that one function, with no exceptions. The Local Variable may be of any data type to be used within the function. It may be any size, within JavaScript limits. In declaring a Local Variable within a function, always use the var keyword to avoid confusing the JavaScript engine.

A variable can be said to be a Global Variable if it is declared outside of the bounds of a function. It must exist on its own. In the declaration of a Global Variable, the programmer is making available the information contained within the variable to every function and statement within that document, as well as the functions and statements represented in an external JavaScript Library. It may be of any data type that will be used within the applicable functions.

It is entirely possible for two variables with different contents, or even the same contents, to exist at the same time providing one is a Local Variable and one is a Global Variable. This case is normally used when the contents of the variable will not change, and must be used within a function as a Local Variable, then outside of a function as a Global Variable.

Creating and Naming Variables

Creating a variable is perhaps the most basic use of the powers of JavaScript. It is done with one statement that can be as small or as large as you have a need for. The name of the variable is typically something descriptive of its content. This makes it easier for you to understand its contents at a later date and time. It also makes it easier for others to understand your approach to the given problem. There are a few things to keep in mind while naming your variable. The list below examines each.

The first character of a valid variable name must be a letter or an underscore. Numbers, punctuation marks and special characters are not tolerated under any circumstances.

There can be any amount of alphanumeric characters following the first character, not including punctuation marks and special characters.

All characters must conform to the basic definition of the ISO-Latin-1 character set.

The letters used may be upper or lower case letters, although JavaScript does distinguish between the two cases. For example, the variable named variableOne is different in the eyes of JavaScript from the variable named variableOne. Case matters when referencing variable names.

Keeping these simple rules in mind is clearly a very easy thing to do when naming your variables. Once you have discovered what data you'd like to store in a variable, it is time to think about naming that variable. Creating the variable is an easy task, of which there are four common variations, shown below.

1. var variableName, variableName, variableName; - You can see in this syntax example that there are three variables being declared at once. You may declare as many variables as you have a need for on one line. Keep in mind that the variables declared in this manor are without values assigned to them. They are empty, and merely exist until you stuff something into them.

2. var variableName = value; - This syntax example shows the creation of one variable. The variable has been assigned an initial value with the value addition to the end of the statement.

3. variableName; - This example shows the creation of a variable without the use of the var keyword. This is an entirely legal thing to do in JavaScript, and saves typing, albeit a small amount. It is recommended you use the var keyword with every variable declaration in order to curtail any problems you may have with variable scope definitions.

4. variableName = value; - This example shows the creation of a variable without the use of the var keyword. This is an entirely legal thing to do in JavaScript, and saves typing, albeit a small amount. It is recommended you use the var keyword with every variable declaration in order to curtail any problems you may have with variable scope definitions. You can see that an initial value has been assigned to the variable, which can be used at a later time.

You can see in the above list that the "var" keyword isn't always necessary - JavaScript is considered to be a "loosely typed" language. This means that there is a lot of flexibility in the way you write your code. Notice also that every way of declaring a variable ended with a semi-colon. This too isn't absolutely necessary for JavaScript. The JavaScript engine takes educated guesses concerning the omitting of semi-colons, and is usually correct in its assumptions - though not always. Ideally, you should remember to end every line of code with a semi-colon. It is a good programming convention that takes the guesswork out of execution by the JavaScript engine. It is recommended you use the semi-colons at the end of every line.

The below example shows the creation of four variables

<SCRIPT LANGUAGE="JavaScript">
<! --

var globalOne = "This is ";
globalTwo = "a string";

function writeVariables() {
var localOne = " of text";
document.write(globalOne, globalTwo, localOne);
}

-- >
</SCRIPT>


The example shows the creation of a variable called globalOne using the var keyword, the content of which is the string "This is ". It is of the String data type because it is enclosed within double quotes, as stated in an earlier section. Next comes another variable called globalTwo that doesn't use the var keyword, but is still a valid JavaScript variable. It is given the value of "a string" which again is a string value because of the nesting of the text within double quotes. Then comes the function, named writeVariables. In this function is the local variable fittingly called localOne. It too contains a string value - " of text". Notice that a space has been left at the front of the text. JavaScript will honor one space appearing before the contents of a string variable, but no more. That is, if you put one space within the text at the beginning of the string and tell the browser to write it, the browser will write that one space. But if you insert more spaces than one, JavaScript will disregard the rest. The document.write statement is then used to reference, then write the contents of the three variables to the browser screen (that's what a document.write statement does - more later). The output of the script looks as follows:

This is a string of text

There is more that you can do with variables, but for now this example is just to give you an idea of how the variable is declared, and a bit about the use of the variable. Almost all of the coming discussions on the JavaScript language involve the use of variables in one form or another, so you'll learn how to think in terms of variables as you go. You can see that there is nothing to declaring, naming, and working with variables. The makers of JavaScript have made it very easy on you, the budding web developer. Enjoy.
Arrays

JavaScript is probably the most forgiving language in existence when thought of in terms of data types and their conversions from one data type to another. The JavaScript engine does everything for you. In languages like the many flavors of C, you have to explicitly change the type of data with a statement before it can be used with another data type. This makes for a very tedious job when working with more than one data type, needlessly adding complexity.

JavaScript allows a variable to hold any data type at any time. A situation where this might be useful is when processing user information - the user inputs a string of numbers and you use this input to calculate something-or-other. You would of course use numbers in your calculation. JavaScript will automatically change the data type from the string type the user has input from the web page form to the Number data type so it can be used as part of the calculation. You'll run into many instances where the data type will be changed on the fly according to circumstances. The change of data type, if applicable, is given for each object, method, array, and property within the JavaScript Language Reference.

JavaScript Arrays

An Array is used to hold a piece or many pieces of information. In JavaScript, an array can hold one data type or all types - JavaScript just doesn't care. In languages such as the C flavors, an array can hold only one data type, which can cause headaches in implementation.

The items of an array are numbered starting from the number 0 (zero) and up. There is really no limit on the size of an array. This numbering system is called a Zero Based Index, and will be referred to as such in the coming discussions. The arrays you'll be working with to start with will be of the "shallow" type of array. That is, the array is only one level deep. An array can have an array existing within it - two arrays represented by one name. This type of array is called a MultiDimensional Array, and is considered to be a deep array. An array within JavaScript can be as deep as you have a need for, with the limit being about four levels deep (though I've personally played around with arrays up to twelve levels deep, just for fun). This restriction isn't due to the capabilities of JavaScript, but of the user's computer - you have no idea what the capabilities of the user's machine will be. Working with a very deep array may overwhelm the user's processor. There's a lot of math involved in accessing and working with arrays, though you don't see any of it - it is within the computer's processor and memory.

In the beginning versions of the JavaScript language, there wasn't a real array object to use - the closest was a string of objects with several properties associated with them. Creating your array and working with it is almost as simple as creating and working with variables - it is a simple statement that is easy to understand.

Creating and Naming Arrays

As with variables, naming your array is something of a test in creativity. Name it too long and you'll have to type more than you probably want. Name it too short, and you might not understand what the thing does at a later date. Some advice: use two words, keeping each word about five or six letters long. Capitalize the first letter of the second word to make for easier reading, but keep in mind that JavaScript watches the case of a letter, so the name will have to be repeated letter for letter, exactly. Obviously, you would choose something descriptive which is applicable to the implementation you are attempting.

To create a new array, follow one of the following simple syntax examples, of which there are three variations.

1. var arrayName = new Array() - This is probably the most commonly used way of creating a new array. It initialy holds no values, nor does it have any length associated with it. It merely exists, ready to be worked with. It is empty because nothing is given within the opening and closing brackets, called the parameters of the array.

2. var arrayName = new Array(array size) - This method is used when you know the length of the array you'll be working with, but don't have the data to stuff into it at the time of creation. The array size parameter is a whole number, an integer. You cannot have a fraction of an array exist. This array size parameter is fully accessible to the length property that exists for all array objects. Once you specify the length of an array, you may have empty items within the array, but you can't stuff more items than the array has space for into the array. You must redefine the array using one of the many methods available to the array object. More on that later. The number stated as the length of the array is assumed to be the data item you want to stuff into position one of the array.

3. var arrayName = new Array(data1, data2, data3, etc) - This method of creating an array both defines the length of the array and the data to be held as the items of the array. As stated earlier, the array can be of any size you have a need for. The data1, data2, and data3, parameters are the data that is to be stuffed into the array. The items will be indexed on a first come, first served basis. That is, data1 will be in position 1, data2 will be in position 2, and data3 will be in position 3. This follows in the same manor for every item you stuff into the array using this method.

4. var arrayName = [data1, data2, data3, etc] - This method of creating an array works exactly the same as the syntax example number three, with a few differences. Note that the "new Array" keywords are left out. JavaScript sees this as entirely legal - if square brackets are used to hold the data items instead of brackets.

Notice that for every method of creating an array the "var" keyword is used. This is essential to the creation of an array. There are no exceptions. The array must use the var keyword because it is essentially a higher form of variable. The new keyword must be used because you're creating a new instance of the core JavaScript Array object, with one exception shown in the syntax example, number 4. You may state as many different arrays as you have a need for. You are not limited to one array.

Now that you have a glimmer of how an array is created, we'll build your knowledge by including a working example of how to access the data items within your array. Its really quite easy to do. Examine the example.

var arrayOne = new Array("This ", "is ");
var arrayTwo = new Array("a ", "string ");
var arrayThree = new Array("of " , "text");

document.write(arrayOne[0] + arrayOne[1] + arrayTwo[0] + arrayTwo[1] + arrayThree[0] + arrayThree[1]);


The example begins with the creation of three arrays called arrayOne, arrayTwo, and arrayThree. They are stuffed with data of the String type. This is evident because the data is enclosed within quotes. The document.write statement (which you'll learn to use as we go) then writes the contents of the arrays to the screen. Notice that each array was created with two items per array. Think back to how the numbering system works within an array. Everything starts at zero and counts up from there. From looking at the example, you can figure out that the contents of an array are accessed by stating the name of the array (exactly - case matters, remember) along with its index number. The index number is enclosed within square brackets. Simple. We'll have more examples for you to examine as we go further into working with arrays. The output of the document.write statement looks as follows.

This is a string of text

I should note that when you reference a position within an array that doesn't exist, the JavaScript engine will return a value of undefined.
String Referenced Array Indexes

In the preceding discussions, we've used only the Zero Based Index method of referring to an array. There is another - the String Referenced Array Index. An array referenced in this way doesn't use the numbers within the index to refer to the contents of an array, but on an individual name for each array item. The method for defining an array in this manor is shown below.

var arrayStuff = new Array();
arrayStuff ["stuffOne"] = 50;
arrayStuff ["stuffTwo"] = 60;
arrayStuff ["stuffThree"] = 70;
arrayStuff ["stuffFour"] = 80;

document.write( arrayStuff ["stuffOne"] + "<br>");
document.write( arrayStuff ["stuffTwo"] + "<br>");
document.write( arrayStuff ["stuffThree"] + "<br>");
document.write( arrayStuff ["stuffFour"] );


This may look unduly complicated, but it really isn't once you get a handle for it. It works as follows. The arrayStuff array is created with four values - the numbers 50, 60, 70, and 80. Notice that they are not strings, as they are not enclosed within quotes. Notice also that for each array item, the arrayStuff array name is given. Within the square brackets are the names you wish that piece of data within the array to be referred as. They are strings, due to their being nested within quotes. The items of the array are now referred to as stuffOne, stuffTwo, stuffThree, and stuffFour instead of index 1, 2, 3, and 4. They may be any name you choose, with the norm being toward something descriptive. The contents of the array are referred to in the same way as the use of the zero based index - the index item name is placed within square brackets. Note that stuffOne and "stuffOne" are two different things in the eyes of JavaScript. One is a string data type (due to the value being nested in quotes), and the other isn't. The array items were named as strings, so the quotes are imperative to perform a valid, functioning reference. The output of the following looks as follows.

50
60
70
80


This method of creating and referring to arrays can come in handy when the user has to input a value which will be a string value. That string value can be used as the reference to an item within an array. More scripting isn't needed to refer to the array - the string value will suffice.

Dotted Notation and the String Referenced Array Index

It is entirely possible, when working with arrays, to create and reference the array using what JavaScript is so well known for - dotted notation. Dotted Notation is very easy to understand and is logical and intuitive. Applied to arrays, it makes the declaration of arrays seem to make more sense. In the preceding example of creating a String Indexed array, square brackets were used to provide the reference to the array item using string values. The same may be accomplished using dotted notation to create and refer to the arrays. Examine the below example, which uses dotted notation with the same result.

var arrayStuff = new Array();
arrayStuff.stuffOne = 50;
arrayStuff.stuffTwo = 60;
arrayStuff.stuffThree = 70;
arrayStuff.stuffFour = 80;

document.write( arrayStuff ["stuffOne"] + "
");
document.write( arrayStuff ["stuffTwo"] + "
");
document.write( arrayStuff ["stuffThree"] + "
");
document.write( arrayStuff ["stuffFour"] );


You can readily see the difference and perhaps realize the ease with which you may construct your String referenced arrays. It saves a lot of typing time because the uncommon square brackets and quote combinations aren't used. It is also more readable. The output of the example is exactly the same as the previous example, which follows.

50
60
70
80

The length Property

As mentioned briefly earlier, an instance of the length property is created for every array in JavaScript. You may not be aware of it, but it is done all the same. This length property holds the length of the array. Simple. This length property may also be accessed and changed to accommodate any changes your array must make to be compatible with your script. It is a fairly simple process.

var arrayOne = new Array();
arrayOne[0] = "red";
arrayOne[1] = "green";
arrayOne[2] = "blue";
document.write(arrayOne.length);


The returned value from the above statements is the number 3. Use this method when you need to know the length of your array. While returning the length of your array is great, sometimes you'll have to redefine the length of your array. The below example shows the shortening of an array from three items to two. When an array is shortened is this manor, the last array item is dropped, and is lost forever - sometimes. Some methods available for the shortening of an array will return to the script the value that was in the array just before it was deleted. This is a convention used to ensure you lose no data from your array machinations.

var arrayOne = new Array();
arrayOne[0] = "red";
arrayOne[1] = "green";
arrayOne[2] = "blue";

document.write("The length of the array originally is " + arrayOne.length + "
");
arrayOne.pop();
document.write("The length of the array after the pop is " + arrayOne.length);


The example first creates the array and populates it with stuff (the strings "red", "green", and "blue"). The length of the array is then written to the screen using a document.write statement. The length returned is three. The array is "popped" using the pop() method (more on methods available to the Array object soon), deleting the last item of the array. The length of the array is then written again with another document.write statement, showing that the length of the array is now 2. The output should look as follows.

The length of the array originally is 3
The length of the array after the pop is 2


You can see that working with your arrays is a very easy business. The methods you employ are rational and logical. The above example shows the use of the pop() method on the array. There are many more methods available to you to manipulate your arrays to suit your needs. The list is as follows.

join() - The join() method is used to concatenate all of the array items into one string. No data is lost during this method.
reverse() - The reverse method is used to reverse the order of the items of the array. The item that is last will become first, and the first the last. No data is lost during this method.
sort() - The sort() method is used to sort the items of the array according to the parameter you specify. The default is alphabetical, with the "A" at the top (position one) of the array and the "Z" at the bottom. No data is lost during this method.
concat() - The concat() method is used to concatenate an array to another aray. The items of the second array are added to the end of the first array. No data is lost during this method.
slice() - The slice() method is used to return a section of the array according to the parameters you specify.
splice() - The splice() method is used to remove the given item from the array. Use the array index number or string representation to specify the aray item to be removed.
push() - The push() method adds an item to the end of the array, increasing the number by one (if you don't define a parameter).
pop() - The pop() method is used to delete an item from the end of the array. The data is removed from the array but is returned to the function so you can use it if you wish.
unshift() - The unshift() method adds an array item to the beginning of the array. The item in position one is moved down to position two. Position two goes down to three, etc. No data is lost during this method.
shift() - The shift() method deletes the first item from an array. The data is removed from the array but is returned to the function so you can use it if you wish.
toString() - The toString() method converts the contents of the array to strings. No data is lost during this method - it is converted to a string.
toSource() - The toSource() method converts the contents of the array to strings contained by square brackets. No data is lost during this method.

A complete and in depth explanation, with examples, is available for all of the above methods in the JavaScript Language Reference, Object Methods.

The MultiDimensional Array

As stated earlier, an array may be made multidimensional. That is, an array can exist within another array and be represented by the same name. There is no limit to the number of dimensions within your array but the norm is to limit yourself to a maximum of four so as to not overwhelm your user's computer and to not create undue complexity. A multidimensional array can be thought of as two arrays side by side in two columns. Although you could create the arrays with string names for each item, it is recommended you use the zero based index method to decrease complexity. Examine the example below that shows the creation of a multidimensional array. The array contents are then written to the screen.

stuffOne = new Array("10", "20", "30");
stuffTwo = new Array("40", "50", "60");

completeArray = new Array(stuffOne, stuffTwo);

document.write(completeArray[0][0] + "<br>");
document.write(completeArray[0][1] + "<br>");
document.write(completeArray[0][2] + "<br>");
document.write(completeArray[1][0] + "<br>");
document.write(completeArray[1][1] + "<br>");
document.write(completeArray[1][2] + "<br>");


The example shows the creation of two arrays called stuffOne and stuffTwo. Each array contains three items which are strings due to the fact that they're within quotes. The completeArray array is then made which references the stuffOne and stuffTwo array. Since the order is stuffOne then stuffTwo, stuffOne will be in the first "column" in the newly created multidimensional array, with stuffTwo being in the second "column". The method for referring to an item within a multidimensional array is shown nicely here. Two sets of square brackets must be used. Remember that the index is zero based - this doesn't change for a multidimensional array. The first square bracket represents the array items in the first array (column1). The second set of square brackets represent2 the array items in the second array (column2). Each of the items within the multidimensional array are referenced, then written to the screen through the means of a few document.write statements. The output of the example is as follows.

10
20
30
40
50
60

The JavaScript Array

I'm including the JavaScript methods for working with arrays here for those older applications that will some day require your attention. They work a bit different because in that version of JavaScript, there wasn't a self-replicating array object like the kind available to more recent version (starting with JavaScript 1.2). To create the equivalent to an array with this version of the language, you need to first create and instance of the Object() object and name it. You would name it something descriptive, of course. Once created, you may assign to the Object object the properties you require using the [ ] operators to stuff values into the object. You must keep track of the length of the array on your own - this version of JavaScript doesn't recognize the length property of the more recent versions. By assigning a length property to the object and assigning a value to it, you may be able to return the length of the array. The downside to this workaround is that the newly created length property will be an item of the array and occupy the number one position. Since the Zero Based Index method is used, length will be in position [0]. Examine the example below.

var arrayStuff = Object();
arrayStuff.length = 3
arrayStuff [1] = " red";
arrayStuff [2] = " green";
arrayStuff [3] = " blue";
document.write("The contents of the array are : " + arrayStuff[1] + arrayStuff[2] + arrayStuff[3])


The example shows first the creation of a new Object() object. The first position of the hypothetical array is taken by the length property, which is set to 3. The rest of the array is created with the values of red, green, and blue - which are strings because they're within quotes. Referencing of the array contents start at position [1] instead of position [0] because the length property occupies position [0]. Simple. The output of the above example is shown below.

The contents of the array are : red green blue

Now since we included a length property in the example, we might as well use it. Examine the following variation of the above example which utilizes the length property within a for statement (which you'll learn more about eventually - be patient).

var arrayStuff = Object();
arrayStuff.length = 3
arrayStuff [1] = " red";
arrayStuff [2] = " green";
arrayStuff [3] = " blue";

document.write("The contents of the array are : ");

for (n=1; n<=arrayStuff.length; n++) {
document.write(arrayStuff[n], " ");
}


The example shows the use of the length property of the arrayStuff object being used within a for statement. The conditional statement as the condition of the for statement, which is within the brackets, takes the value of the length property and increases it by one. This is your first instance of seeing a loop function. The initial value is 1 because the length property is in position 0 within the array - arrays are zero based indexes. The number of the index is represented by the letter n which initially has a value of one as defined by the "n=1" statement. This value of n is then referred to the arrayStuff.length property with the "n<=arrayStuff.length" statement. Finally, the value of n is increased by one with the "n++" statement using the "increase by one" JavaScript operator. Within the opening and closing braces of the for statement is a document.write statement which calls upon the condition within the brackets of the for statement. The position within the array is represented by the letter n within the square brackets, telling the browser to interpret the condition within brackets until it runs out of items in the arrayStuff array. The results are written to the screen and should look as follows.

The contents of the array are: red green blue

Thatís it for arrays. You now have the knowledge required to advance on to the more in depth JavaScript statements such as conditional expressions and loops. Variables and arrays are used extensively in these operations. Read on.
Operators

An operator in JavaScript is said to be any symbols or group of symbols that performs a very specific function, usually on numbers. Operators are used extensively in JavaScript because of there flexibility - they can be applied not only to numbers, but in special cases can also be applied to strings and other data types. Many of the mathematical functions of operators bring data type conversion into play. The rules for data type conversion are given here and in the JavaScript Language Reference, Operators. There are seven general types of operators, as follows.

Arithmetic Operators
The String Operator
Assignment Operators
Logical Operators
Comparison Operators
The Conditional Operator
Bitwise Operators

Each has its own set of rules governing its use and functionality. Each general class has several different operators that you must have an understanding of in order to move on to the higher functions such as loops and conditional statements. Each general type of operator is described in detail in the coming sections. Each operator is also defined in depth and with working examples in the JavaScript Language Reference, Operators.

Arithmetic Operators

An arithmetic operator obviously works with numbers and is used within arithmetic operations. There is a wide variety of operators to work with, from the simple to the advanced. There are many built in mathematical functions to the JavaScript language that are covered in the Numbers Data Type section. Since we've already looked at them, we'll not include them here. There are, however, many different functions available through the Math object. These mathematical methods are listed below.

Math.abs() - This method is used to calculate the absolute value of a number.
Math.acos() - This method is used to calculate the arc-cosine of a number.
Math.asin() - This method is used to calculate the arc-sine of a number.
Math.atan() - This method is used to calculate the arc-tangent of a number.
Math.atan2() - This method is used to calculate the arctangent of the quotient of its given parameters.
Math.ceil() - This method is used to calculate the ceiling of the numbers being worked with.
Math.cos() - This method is used to calculate the cosine of a number.
Math.exp() - This method is used to calculate the natural exponent of a number.
Math.floor() - This method is used to return the floor value of the numbers being worked with.
Math.log() - This method is used to calculate the natural logarithm of a number.
Math.max() - This method is used to calculate the maximum value for the two parameters passed.
Math.min() - This method is used to calculate the minimum value for the two parameters passed.
Math.pow() - This method is used to calculate the power of the number passed as the parameter.
Math.random() - This method is used to calculate a random number.
Math.round() - This method is used to round the number given to the nearest whole number.
Math.sin() - This method is used to calculate the sine of a number.
Math.sqrt() - This method is used to calculate the square root of a number.
Math.tan() - This method is used to calculate the tangent of a number.

Each of the above methods, used with the Math object, give a wide array of functionality to your scripting actions. They may be used alone or in combinations. All of the common arithmetic operators will attempt to convert strings to numbers. If this is not possible, the NaN (Not A Number) data type will be returned. While the above listing is a list of mathematical methods, the following is a list of arithmetic operators, which are different from methods. Each is explored in detail. Again, all of the following are available in an in depth form in the JavaScript Language Reference, Operators.

Addition ( + ) - The addition operator is the most commonly used operator. It is obviously used to add two numbers together. When the values on either side of the addition operator are numbers, they are added together. When they are strings, they are concatenated, the second being appended to the end of the first. If a number and a string are being added, the string is converted to a number, then added to the other number. If this conversion is not possible, NaN is returned.
Subtraction ( - ) - The subtraction operator is used in subtraction. The subtraction operator subtracts the right number from the left. If either or both of the values are strings, an attempt is made to convert them to numbers. If this is not possible, the value of NaN is returned.
Multiplication( * ) - The multiplication operator is used to multiply the left value by the right. When the values on either side of the multiplication operator are numbers, they are multiplied together. When they are strings, they are converted to numbers. If a number and a string are being added, the string is converted to a number, then multiplied by the other number. If this conversion is not possible, NaN is returned.
Division ( / ) - The division operator is used to divide the left value by the right value. If either or both of the values are a string, an attempt is made to convert the string to a number. If this is not possible, NaN is returned.
Modulus ( % ) - The modulus operator is an interesting one. It is used to return the remainder of the division of the two values given. Neat. As with the division operator, the left value is divided by the right. If either or both of the values are a string, an attempt is made to convert the string to a number. If this is not possible, NaN is returned.
Pre-Increment ( ++value ) - The pre-increment operator is a very useful and time saving operator. It is used to increase the number given by one, then return that new, incremented number. If either or both of the values are a string, an attempt is made to convert the string to a number. If this is not possible, NaN is returned.
Post-Increment ( value++ ) - The post-increment operator is used to increase the given number by one, but even though the new, decremented number is saved within the variable, it is not returned - the original number is. If either or both of the values are a string, an attempt is made to convert the string to a number. If this is not possible, NaN is returned.
Pre-Decrement ( --value ) - The pre-decrement operator is used to decrease the number given by one then return that new, decremented number. If either or both of the values are a string, an attempt is made to convert the string to a number. If this is not possible, NaN is returned.
Post-Decrement ( value-- ) - The post-decrement operator is used to decrease the given number by one, but even though the new, decremented number is saved within the variable, it is not returned - the original number is. If either or both of the values are a string, an attempt is made to convert the string to a number. If this is not possible, NaN is returned.
Unary Negation ( - ) - The unary negation operator is used to change the polarity of a number. That is, it converts a positive number to a negative number. You might have noticed that the Unary Negation operator is the same as the subtraction operator. Only its use differs. Use it in front of a positive number to change it to a negative number. Use it in front of a negative number to change it to a positive number. If either or both of the values are a string, an attempt is made to convert the string to a number. If this is not possible, NaN is returned.
The String Operator

The one and only string operator is actually the addition operator. As shown in the addition operators section, the addition operator is also a string concatentor. With it you can combine two strings together, the second to the end of the first. This has many practical uses, as you'll see as your skills develop. If a number and a string are being used, the string is converted to a number, then added to the other number. If this conversion is not possible, NaN is returned. See the below example to get a feel for string concatenation.

variableOne = new String("50");
variableTwo = variableOne + 20;

document.write("The contents of variableOne is " + variableOne);
document.write("The contents of variableTwo is " + variableTwo);


The example shows string concatenation, since every one understands simple addition. variableOne has the string "50" loaded into it, and variableTwo is the concatenation of the variableOne value and the number 20. The result of the first document.write statement is 50, while the result of the second document.write statement is 5020, the two values, concatenated.

Assignment Operators

The assignment operators are used to assign values to variables. The most common assignment operator is the "equals" operator represented by an equals sign. Check out the example that shows the assignment of the number 50 to the variable variableOne.

variableOne = 50;

You can see that there's nothing to it - with the equals assignment operator. The others get a bit more complicated and delve into the concepts of logic and equivalency. Basically, the rest of the assignment operators are used to perform algebraic and Boolean functions. Examine the below list of assignment operators.

= - Assignment - X=Y - The Assignment operator is perhaps the simplest and most commonly used of all of the operators. It is used within a variable, for example, to assign the following value to the preceding variable name.
+= - Add By Value - X=X+Y - The add by value operator is also known as the "Addition Assignment" operator. It is used to add the value on the right of the add by value operator to the value on the left of the add by value operator, the result of which replaces the variable value on the left of the operator. If neither of the operand values are strings or numbers, they will be converted to numbers. This operator can also be used for string concatenation. That is, the joining of two words (strings) or numeric characters together to form one string. Again, the operand on the right is concatenated to the operand on the left, and the left operand is overwritten with the new value. If one of the operands is not a string, it is converted to a string, then concatenated.
-= - Subtraction Assignment - X=X-Y - The subtraction assignment operator is used to subtract the number on the right of the operator from the number stored as a variable to the left of the operator. The result of the operation overwrites the value stored in the variable to the left. If either of the operands is a string, it is converted to a number. If this is not possible, NaN is returned.
*= - Multiplication Assignment - X=X*Y - The multiplication assignment operator is used to multiply the number stored as a variable on the left of the operator by the number to the right of the operator. The result of the operation overwrites the value stored in the variable to the left. If either of the operands is a string, it is converted to a number. If this is not possible, NaN is returned.
/= - Division Assignment - X=X/Y - The division assignment operator is used to divide the number stored as a variable on the left of the operator by the number to the right of the operator. The result of the operation overwrites the value stored in the variable to the left. If either of the operands is a string, it is converted to a number. If this is not possible, NaN is returned.
%= - Modulus Assignment - X=X%Y - The modulus assignment operator is used to divide the number stored as a variable on the left of the operator by the number to the right of the operator. The remainder of the operation is returned, overwriting the value stored in the variable to the left. If either of the operands is a string, it is converted to a number. If this is not possible, NaN is returned.
<<= - Shift Right with Sign Assignment - X=X<<Y - The shift right with sign assignment operator looks at the number to the left of the operator as a 32 bit binary number. The bits of this binary number are then shifted to the right the number of places within the variable to the right of the operator. There are a couple of rules to be examined. If the original number shifted out of existence is a one, zeros are filled. If the original number is a zero, ones are filled. These numbers are filled to keep the binary number at an even 32 bits. The bits on the right of the binary number are lost. The result is then converted to a decimal integer and stored in the variable to the left of the operator.
>>= - Shift Left with Assignment - X=X>>Y - The shift left with sign assignment operator looks at the number to the left of the operator as a 32 bit binary number. The bits of this binary number are then shifted to the left the number of places within the variable to the right of the operator. There are a couple of rules to be examined. If the original number shifted out of existence is a one, zeros are filled. If the original number is a zero, ones are filled. These numbers are filled to keep the binary number at an even 32 bits. The bits on the left of the binary number are lost. The result is then converted to a decimal integer and stored in the variable to the left of the operator.
>>>= - Shift Right Zero Fill with Assignment - X=X>>>Y - The shift right zero fill with sign assignment operator looks at the number to the left of the operator as a 32 bit binary number. The bits of this binary number are then shifted to the right the number of places within the variable to the right of the operator. Regardless of the sign of the original binary number, the numbers filled used to "fill" the places now deleted are zeros. No exceptions. These numbers are filled to keep the binary number at an even 32 bits. The bits on the right of the binary number are lost. The result is then converted to a decimal integer and stored in the variable to the left of the operator.
&= - Bitwise AND Assignment - X=X&Y - The bitwise AND assignment looks at the numbers on both sides of the operator as 32 bit binary numbers. The logical AND operation is then carried out on each bit of the 32 bit binary number. The result is converted to a decimal integer and stored in the variable to the left of the operator.
|= - Bitwise OR Assignment - X=X|Y - The bitwise OR assignment looks at the numbers on both sides of the operator as 32 bit binary numbers. The logical OR operation is then carried out on each bit of the 32 bit binary number. The result is converted to a decimal integer and stored in the variable to the left of the operator.
^= - Bitwise Exclusive OR Assignment - X=X^Y - The bitwise exclusive OR assignment looks at the numbers on both sides of the operator as 32 bit binary numbers. The logical exclusive OR operation is then carried out on each bit of the 32 bit binary number. The result is converted to a decimal integer and stored in the variable to the left of the operator.

You can see that there is lot to the assignment operators. With this abundance of information comes an abundance of abilities - refer to the JavaScript Language Reference when you're in doubt as to what each does or even if the operator you have a need for exists. Chances are it does.
Logical Operators

The logical operators are mostly Boolean operators. For those of you familiar with Electronics or Boolean Algebra, this section will make a lot of sense to you. If not, read on. It will. There are only three logical operators to JavaScript - the Logical AND, the Logical OR and the Logical NOT operators. Each has its own set of rules governing its abilities, and each is used differently, as seen below.

&& - Logical AND - The logical AND operation is fairly simple to understand. An AND operation involves the use of two expressions. The logical AND operator returns a value of true if the expression to the left and the expression to the right of the operator evaluate to true. If either the left, the right, or both of the expressions evaluate to false, then a value of false is returned from the operation. It is very important to understand how the true or false results are computed. The operation begins by evaluating the left operand. If it is found to be false, then the basic AND operation is completed - the right operand isn't evaluated. If the left operand is found to be true, then the right expression is evaluated. In either case, the true or false result of the last expression evaluated is the result that will be returned. Examine the following table, called a Truth Table.

Logical AND (&&) Truth Table
Left Operator AND Right Operator Result
________________________________________

TRUE AND TRUE TRUE
TRUE AND FALSE FALSE
FALSE AND TRUE FALSE
FALSE AND FALSE FALSE


|| - Logical OR - An OR operation involves the use of two expressions. The logical OR operator returns a value of true if the expression to the left OR the expression to the right of the operator evaluate to true. If the left OR the right of the expressions evaluate to true, then a value of false is returned from the operation. It is very important to understand how the true or false results are computed. The operation begins by evaluating the left operand. If it is found to be true, then the basic AND operation is completed - the right operand isn't evaluated. If the left operand is found to be false, then the right expression is evaluated. In either case, the true or false result of the last expression evaluated is the result that will be returned. Examine the following Truth Table.

Logical OR (||) Truth Table
Left Operator OR Right Operator Result
________________________________________

TRUE OR TRUE TRUE
TRUE OR FALSE TRUE
FALSE OR TRUE TRUE
FALSE OR FALSE FALSE


! - Logical NOT - The Logical NOT is a bit different than the Logical AND and Logical OR operations. It isn't as complex. The result of the expression following the operator is inverted. If the expression evaluates to true, the result of the operation is false. If the expression evaluates to false, the result of the operation is true. Simple.

Comparison Operators

Comparison Operators are used to compare the operand to the left of the operator to the operand to the right of the operator. A true or false result is returned from the operation. Each functions a little different than does the next, so there's alot to be learned here. Keep in mind that everything is order and logical - there are no weird surprises or quirky rules, just pure logic. The Comparison Operators are discussed below.

== - Equality - The equality operator is used to compare the left operand to the right. If they are the same (equal), then the result returned from the operation is true. Otherwise, the result returned from the operation is false. There are a few general rules to keep in mind when using the equality operator. They are as follows.

1. true is converted to 1 and false to 0 (zero) before being compared.
2. If either of the operands evaluate to NaN, the result returned is false.
3. null and undefined are equal.
4. null and undefined are not equal to 0 (zero) or false or empty (no value).
5. If a string and a number are compared, the string is converted to a number, then compared. If the string cannot be turned into a number, the result is NaN.
7. If an object and a number are compared, an attempt is made to convert the object to a number. If the object cannot be turned into a number, the result is NaN.
8. If two objects are being compared, the addresses of the two objects are checked for equality. If equal, a result of true is returned, if not equal, a result of false is returned.

!= - Not Equal - The not equal operator compares the left operand to the right operand. If the two operands are not equal, a value of true is returned. If they are equal, a value of false is returned.
> - Greater Than - The greater than operator compares the left operand to the right operand. If the value on the left is greater than the value on the right, a value of true is returned from the operation. If the value on the left is less than the value on the right, a value of false is returned from the operation.
< - Less Than - The less than operator compares the left operand to the right operand. If the value on the left is less than the value on the right, a value of true is returned from the operation. If the value on the left is greater than the value on the right, a value of false is returned from the operation.
>= - Greater Than or Equal - The greater than operator compares the left operand to the right operand. If the value on the left is greater than or equal to the value on the right, a value of true is returned from the operation. If the value on the left is less than the value on the right, a value of false is returned from the operation.
<= Less Than or Equal - The less than operator compares the left operand to the right operand. If the value on the left is less than or equal to the value on the right, a value of true is returned from the operation. If the value on the left is greater than the value on the right, a value of false is returned from the operation.
=== - Identity - The identity operator compares the left operand to the right operand. If the value on the left of the operand is equal to the value on the right, true is returned from the operation. If the values are not equal, a value of false is returned from the operation. No type conversion is performed on the operands before the two values are compared for equality.
!== - Non-Identity - The identity operator compares the left operand to the right operand. If the value on the left of the operand is not equal to the value on the right, true is returned from the operation. If the values are equal, a value of false is returned from the operation. No type conversion is performed on the operands before the two values are compared for equality.
The Conditional Operator

Simply put, the conditional operator is the following: "( (expression) ? trueValue : falseValue )". This operator fulfills the same functionality as an if / else statement, but in a kind of shorthanded form. An expression that evaluates to a Boolean (true or false) must be placed to the left of the question mark. If the expression evaluates to true, the first value after the question mark is returned from the operation. If the expression evaluates to false, the value after the colon is returned from the operation. This shorthanded if / else statement is especially useful to decrease the amount of typing you'll have to do. It seems to make more sense to me than does the if / else statement.

The following example, taken from the JavaScript Language Reference, shows the use of both the less-than operator and the conditional operator. It is a simple example that shows the use of the conditional operator very well.

var n = new String("67");
if ((n < 100) ? document.write("The result is true") : document.write("The result is false"));


The example shows the use of the conditional and less-than operators nicely. First the variable "n" is created, which holds the number 67, which is of the string data type. Then an if statement is started with the conditional operator as the condition. The "n<100", which is read as "if n is less than 100", obviously compares to true since the value of n is 67, which is less than 100. This comparison tells the browser to display the "true" result, so the string "The result is true" will be written to the screen. If the result was false, the string "The result is false" would be written to the screen. So much for the conditional operator.

Bitwise Operators

You might notice in our exploration of the bitwise operators that they look very much like the various comparison operators. But in fact they differ hugely in their functionality. A operator is said to be "bitwise" when its values are the direct result of a binary computation of some sort. The given integer is converted to a 32 bit binary number, and then something is done to it. They are indispensable when working with binary numbers (decimal equivalents of binary numbers). If the integer used to represent the binary integer doesn't evaluate to 32 bits long, JavaScript automatically adds on the required amount of zeros to achieve the required 32 bit length.

& - Bitwise AND - The bitwise AND operation looks at the value to the left of the operator and the value on the right of the operator as 32 bit binary numbers. These binary ones and zeros are then ANDed and the result is returned as a decimal integer from the operation.
| - Bitwise OR - The bitwise OR operation looks at the value to the left of the operator and the value on the right of the operator as 32 bit binary numbers. These binary ones and zeros are then ORed and the result is returned as a decimal integer from the operation.
^ - Bitwise Exclusive OR (XOR) - The bitwise XOR operation looks at the value to the left of the operator and the value on the right of the operator as 32 bit binary numbers. These binary ones and zeros are then XORed and the result is returned as a decimal integer from the operation.
~ - Bitwise NOT - The NOT operand is basically an inverter. It changes all of the ones in the 32 bit binary equivalent to zeros and all of the zeros to ones. This new binary number is then converted to a decimal integer and returned as the result of the operation.
<< - Shift Left - The shift left operator is used to shift the binary equivalent of the number to the left of the operator. The number of places to be shifted is given as an integer to the right of the operator. This shifting operation leaves empty places on the right of the 32-bit number. Since the number must always be 32 bits long, zeros are added to the binary number.
>> - Shift Right with Sign - The shift right with sign operator is used to shift the binary equivalent of the number to the left of the operator. The number of places to be shifted is given as an integer to the right of the operator. This shifting operation leaves empty places on the left of the 32-bit number. Since the number must always be 32 bits long, numbers must be added. If the original number is positive, ones are added to make the number 32 bits long again. If the number was originally negative, zeros are added.
>>> - Shift Right Zero Fill - The shift right zero fill operator is used to shift the binary equivalent of the number to the left of the operator. The number of places to be shifted is given as an integer to the right of the operator. This shifting operation leaves empty places on the left of the 32-bit number. Since the number must always be 32 bits long, numbers must be added. Regardless of the polarity of the original number, zeros are added to make the number once again 32 bits in length.
Conditional Statements

Conditional Statements give the JavaScript code you are writing the ability to make decisions or perform single or multiple tasks. These Conditional statements were borrowed from older, more polished languages like C and C++. Porting over the functionality of these very capable languages gives JavaScript a very polished set of useful and functionally correct tools which you, the developer, can work with.

A conditional statement uses the operators that were discussed in an earlier chapter. There are three conditionals used within the JavaScript language, which will be discussed in depth in the coming sections. They are as follows.

The if and if / else Conditional Statements
The else / if Conditional Statement
The switch / case Conditional Statement

Each conditional satisfies a slightly different chunk of functionality needed to make very robust and powerful scripts. Each is implemented slightly different, with an eye toward being able to execute what the previous wasn't able to. Working hand in hand this way, the conditionals are able to perform some very impressive programming feats with a minimum of fuss and typing.

The if and if / else Conditional Statements

The if conditional is used to perform an action "if" the condition is met. Examine the below syntax example to get a feel for how to build a simple if conditional.

if (expression)
statement;


The example shows the if keyword followed by an expression within brackets. Within these brackets are the conditions that must be met in order to execute the statement. If the condition is never met, the statement is never executed. Simply put, the expression must evaluate to true in order for the statement to be executed. Within this simple conditional are an infinite number of variations. Basically, you're letting the script make decisions based on the condition, the expression, you supply.

While performing an action if a value of true is returned from the expression is great, you will eventually have a need for something to happen if the expression evaluates to false. Assigning an action to the false output of the expression involves a very simple addition to the if statement given above. The else keyword is used to supply an action to be taken if the expression is false. Examine the syntax example below.

if (expression) {
statement If expression is True;
} else {
statement If expression is False;
}


Notice the addition not only of the else keyword and an additional statement, but also the use of the opening and closing curly braces - { } . The braces are used to encapsulate the true statement and the false statement, as well as divide the entire statement into its "if" and "else" sections. Notice also that the basic JavaScript syntax rules haven't been broken - a semi-colon is present after both the true statement and the false statement.

This is probably the most common of all of the many JavaScript statements. You'll use it often, so get a feel for it now. We'll examine a couple of working examples to help you get a feel for working with the if and if / else statement.

if (80<100)
document.write("The expression has evaluated to true!!");


You can see the basic if statement used very simply here. Notice the "less-than" operator used within the conditional expression - "80<100". This if statement simply states that if 80 is less than 100, the statement is considered to be true. Since 80 is actually less than 100, the document.write statement is written to the screen. If the conditional expression were "101<100" (which is read as "if 101 is less than 100"), then nothing would be written to the screen as the conditional expression would have evaluated to false. Use the if statement if you want something to happen only if the conditional expression evaluates to true.

If you'd like an action to be taken when the conditional expression evaluates to false as well as true, use the else addition to provide an action to be taken when the conditional expression returns a false value, as shown below.

if (101<100) {
document.write("The expression has evaluated to true!!");
} else {
document.write("The expression has evaluated to false!!");
}


The above if / else statement says that if 101 is less than 100, write the first document.write statement to the screen. If 101 isn't less than 100 the second document.write statement is written to the screen. Since 101 is not less than 100, the conditional expression returns false, and the second document.write statement ("The expression has evaluated to false!!") is written to the screen.

So now that you know the basic structure of the if and if / else statements, we'll delve into another aspect - nesting your if / else statements. This nesting structure is used when you have an initial condition to be met with a true or false value, then you require another set of conditions that you'd like to have tested to acquire your end result. Examine the below syntax example to understand more clearly what is meant by the term "nesting".

if (expression1) {
statement If expression1 is True;
} else {
if (expression2) {
statement If expression2 is True;
} else {
statement If expression2 is False;
}
}


You can see that the second if / else statement is nested within the "false" area of the first if / else statement. If expression1 evaluates to true, then the first document.write statement of the first if / else statement is written to the screen. If expression1 evaluates to false, then the second if / else statement is evaluated. If expression2 evaluates to true, the first document.write statement of the second if / else statement is written to the screen. If expression2 evaluates to false, then the second document.write statement of the second if / else statement is written to the screen. This somewhat complicated (but very useful) method will be used widely within your future JavaScript coding.

To illustrate further, I'll use the nesting of if / else statements in a couple of working examples, shown below.

if (99<100) {
document.write("Expression1 has evaluated to true!!");
} else {
if (80<100) {
document.write("Expression2 has evaluated to true!!");
} else {
document.write("Expression2 has evaluated to false!!");
}
}


The example shows the nesting of an if / else statement within another. The first if / else statement shows the less than operator being used to evaluate the weights of two numbers, 99 and 100. Since 99 is indeed less than 100, the conditional expression returns a value of true, and the first document.write statement ("Expression1 has evaluated to true!!") is written to the screen. The false section of the first if / else statement is never consulted, since the conditional expression of the first if / else statement evaluated to true. Examine the below example, which utilizes the decision making ability of the second, nested, if / else statement.

if (101<100) {
document.write("Expression1 has evaluated to true!!");
} else {
if (80<100) {
document.write("Expression2 has evaluated to true!!");
} else {
document.write("Expression2 has evaluated to false!!");
}
}


Since 101 is less than 100, and the conditional expression of the first if / else statement returns false, the second if / else statement is executed. Since 80 is less than 100, the conditional expression returns a value of true and the first document.write statement of the second if / else statement is executed, writing "Expression2 has evaluated to true!!" to the screen. Simple.
The else / if Conditional Statement

The else / if statement is used to make your script supposedly more readable. I don't concur, preferring to use the if / else structure in all of my scripting. It performs the same actions as does the if / else statement. Examine the syntax example given below.

if (101<100)
document.write("Expression1 has evaluated to true!!");
else if (80<100)
document.write("Expression2 has evaluated to true!!");
else
document.write("Expression2 has evaluated to false!!");


You can see that the curly braces required for the if / else statement aren't in attendance. They simply aren't necessary. The above script works the same as does an if / else statement nested within another if / else statement. So much for the else / if conditional statement.

The switch / case Conditional Statement

The switch / case conditional statement is used to test all of the possible outcomes for the application you are designing. Used with the case keyword, the switch statement can give you the control you require, with many actions possible instead of just the two given with an if / else statement. That is, you are not limited to a true or false answer to decide between only two actions. While the true or false decision is still used at a very basic level, you may have as many outcomes as you have a need for. Examine the syntax example, given below.

switch (expression)
{
case caseLabel:
statement;
break;
case caseLabel:
statement;
break;
case caseLabel:
statement;
break;
default:
statement;
}


Notice the colons following the case and caseLabel keywords. This is absolutely required. Don't leave them out. Don't substitute the colons with semi-colons, or your script won't work. And don't forget the colon following the default keyword near the end of the script. The switch statement begins with, of course, the switch keyword. Within the brackets following the switch keyword is the expression, which is used to set the parameter that the rest of the script will use as the data to be used to make a decision. Once this decision is made, the script looks for a match among the various case keywords. Each case keyword has a unique caseLabel associated with it. This is used to define each case statement as a unique and individual entity to your script. Once a case with the matching caseLabel is found, the statement within the case statement is executed. On the end of the switch statement, you'll see that a "default" keyword was used, with a statement of its own given. This default statement is executed when none of the given cases match the expression given in brackets following the switch keyword. Notice also that break; statements were used. The break statements used in this way are required to "break" out of the switch / case structure and go on to further actions. It is required so that the rest of the case options below the selected case (as well as the default actions) aren't executed. To further illustrate the concept, examine the following working example which utilizes the switch / case statement.

var varOne = 100;

switch (varOne)
{
case 90:
document.write("The value of varOne is 90");
break;
case 100:
document.write("The value of varOne is 100");
break;
case 110:
document.write("The value of varOne is 110");
break;
default:
document.write("The value of varOne is unKown");
}


The example shows the declaration of a variable, varOne. varOne contains a number, which is 100. This varOne variable is then used as the expression of the switch statement. Now that the script has the expression with to find a match, the several cases given are searched until a case is found that matches the varOne value, which is 100. Since the second label matches the varOne value given as the expression, the statement within that case statement is executed, which is a document.write statement which writes the words "The value of varOne is 100" to the screen.

It should be noted that you aren't limited to using a variable with a static, unchanging value. You may use a variable that changes dynamically with either user driven or script driven actions associated with it to obtain a changing value.
Loops

Loops give the JavaScript code you are writing the ability to make decisions (with the Conditional part of the statement) or perform a single task as many times as you have a need for. These Conditional and Looping statements were borrowed from older, more polished languages like C and C++. Porting over the functionality of these very capable languages gives JavaScript a very polished set of very useful and functionally correct tools which you, the developer, can work with.

Basically, a loop is just that - an action that occurs again and again until a certain condition, set by you, is met, thus satisfying the condition of the loop and stopping the looped action. Used with the many operators available to JavaScript, there is no limit on what your looped expressions can do. There are four different loop structures and three different statements that will be discussed in this document. They are as follows.

The for Loop
The while Loop
The do / while Loop
The for / in Loop
The break Statement
The continue Statement
The with Statement

The break, continue, and with statements are used within the loop statements to provide a very specific functionality that would either be non-existent or be very tedious. The statement is there to help you, the developer, in writing more efficient code with a smaller amount of typing. They are fairly simply to use and are very straightforward. There's no big tricks or hidden functionality, just well designed and fully functional commands.

The for Loop

The for loop is perhaps the most widely used of all of the loops available to JavaScript. It was designed to be close in functionality to the for loop available to the C and C++ languages. The main difference is its treatment of data types. As mentioned in previous discussions JavaScript does its own data type conversions, making it extremely simple to work with more than one data type.

The for loop is made of two separate parts - the condition and the statement, as shown below in the syntax example.

for (initialValue ; condition ; adjustInitialValue)
{
statement
}


The condition of the for loop is the three values (initialValue, condition, and adjustInitialValue) within the opening and closing brackets after the for keyword. The statement is the statement given within the curly braces. The statement is executed on the variable declared for initialValue and then on adjustInitialValue. The loop iterates through itself until the condition is satisfied, no matter how long it takes. Care should be taken to not create an infinite loop that has a condition that won't ever be satisfied by the rest of your script.

The initialValue is a variable that defines the initial starting value for the loop. This variable can be defined within the loop or by a separate variable declaration not within the loop. Take care that the variable is of the Global type of variable - JavaScript does not allow the use of a Local type of variable outside of the function it was created in. The condition is the section in which you'll use the operators learned in a previous discussion. It is used to provide the amount of times to iterate through the loop. The third section of the loop is adjustInitialValue, which is used to make an adjustment to the initialValue section. This adjustment may be any increment, decrement, or any other operation you may have a use for. Obviously, the adjustment would reflect the type of data you are using and the outcome you were looking for.

The below example shows the use of a loop very well. It is used to print the multiplication table of 5, up to 5 X 12.

for (var varOne = 0 ; varOne <= 12 ; varOne++)
{
document.write("5 X " + varOne + "=" + 5*varOne + "
");
}


The example shows the for keyword followed by the initial value within the newly created variable, varOne. The value of varOne is initially zero. The next part of the statement tells you that the maximum amount of times the loop is to iterate is 12 times, as indicated by the "varOne <= 12" statement. Next comes the statement that changes the initial value of zero within varOne. In this case the change is a simple post-decrement operator that increases the value of varOne by One. After each iteration, the document.write statement is printed to the screen. The document.write statement does the multiplication used to display the multiplication by five results, not the loop condition. The output looks as follows.

5 X 0=0
5 X 1=5
5 X 2=10
5 X 3=15
5 X 4=20
5 X 5=25
5 X 6=30
5 X 7=35
5 X 8=40
5 X 9=45
5 X 10=50
5 X 11=55
5 X 12=60


You can see now how simple it is to create a for loop. This is most likely the reason why it is used so often.
The while Loop

The while loop has all of the functionality of the for loop, but with a few exceptions - there is no provision within the statement to tell the script how many times to iterate through the statement. An infinite loop is not very common but in some very rare cases is actually the desired result. Also, the statement is executed only if the expression evaluates to true. If it evaluates to false, the statement following the while statement within your script is executed. Examine the syntax example, shown below.

while (expression)
{
statement;
}


It should be noted that because the expression is evaluated before the loop is started, it is very possible that the loop will never be executed should the expression evaluate to false the very first time. Examine the below working example of a very simple while loop.

var varOne = 0;
while (varOne <= 12)
{
document.write("5 X " + varOne + "=" + 5*varOne++ + "
");
}


This example does the same as the for example covered earlier does - it iterates through itself, writing the multiply - by - five multiplication tables up to 5 X 12 = 60. A few things were done differently within the while loop. First, the variable "varOne" that you were able to declare within the conditional part of the for loop had to be declared as a Global Variable. The value of varOne is still an initial value of zero. Next comes the while keyword followed by the expression to be evaluated, "varOne <= 12". This statement says that the value of varOne may be less than or equal to 12 and still evaluate to true. Keep this in mind for a minute. Within the document.write statement, you'll see some applicable text written to the screen as well as the statement "5*varOne++". This statement multiplies the number 5 by the number in varOne, which in the first iteration through the loop will be zero. After this multiplication comes the post-increment operator, which increases the value of varOne by one. The expression "varOne <= 12" is then tested again. This goes on until the value of varOne is greater than 12 because the statement "varOne <= 12" will return a value of false when varOne is greater than 12, breaking out of the loop. Simple. The output to the above example is given below.

5 X 0=0
5 X 1=5
5 X 2=10
5 X 3=15
5 X 4=20
5 X 5=25
5 X 6=30
5 X 7=35
5 X 8=40
5 X 9=45
5 X 10=50
5 X 11=55
5 X 12=60


The do / while Loop

The do / while loop differs from the basic while loop in that the loop is executed once before the expression is tested, ensuring that the statement given is always executed at least once. Examine the syntax example below.

do
{
statement;
}
while (expression);


If the expression evaluates to true, the loop is iterated through once more and the statement is executed again. When the expression evaluates to false, the loop is broken and the do / while statement is exited. As with all JavaScript statements, data type conversion is performed on the fly, so it is extremely unlikely that you'll have a problem due to varying data types. It should be noted that the do / while statement will not work if you omit the semi-colon following the line "while (expression)". Don't forget it, it is one of the very few strictly enforced rules within JavaScript. Examine the working example given below of a do / while loop, again iterating through the multiply-by-five times table up to 5 X 12 = 60.

var varOne = 0;
do
{
document.write("5 X " + varOne + "=" + 5*varOne++ + "
");
}
while (varOne <= 12);


The example begins with the declaration of a variable called varOne, which initially holds a numeric value of zero. The do keyword follows, then the document.write statement. Within the document.write statement you can see the line "5*varOne++" which multiplies the contents of varOne by five, then increments the value of varOne by one through the use of the post-increment operator. The while statement is then evaluated. If true, the loop iterates once more. If false, the loop is broken and the line following the while statement is executed by the JavaScript engine. The number of times the loop iterates is set by the "while (varOne <= 12);" line, which states that the expression will evaluate to true if varOne has a value less than or equal to 12. When the value of varOne is greater than 12, the loop is broken. The output of the above example is shown below.

5 X 0=0
5 X 1=5
5 X 2=10
5 X 3=15
5 X 4=20
5 X 5=25
5 X 6=30
5 X 7=35
5 X 8=40
5 X 9=45
5 X 10=50
5 X 11=55
5 X 12=60

The for / in Loop

The for / in loop doesn't have much in common with the for loop. Aside from the fact that each loop is iterated through a set number of times, that's were the similarity stops. The for / in loop is used to access all of the properties of a fully qualified JavaScript Object. These objects also include arrays because some properties of an array are stored in the same way as is the properties of a common JavaScript object. Examine the syntax example, given below.

for (variableName in objectName)
{
statement;
}


The statement within the loop is executed upon every property within the given objectName. Before the statement within the loop is executed, a property of the objectName is assigned to the variableName. The variable and its contents is then used by the loop. This process of assigning the properties of the objectName to the variableName continues until all of the properties of the objectName are accessed. The order in which the properties of objectName are accessed does not follow any set of rules, so the order in which they are accessed might not always be the same. You'll have to alter your script to concede to this. Examine the working example below.

var buttonProperties; for (buttonProperties in document.form1.inputButton)
{
document.write(buttonProperties, " + "
");
}


The example assumes you have the following within the BODY of your document.

<FORM NAME="form1">
<INPUT TYPE="button" NAME="inputButton" VALUE="Input Now">
</FORM>


The script that is used to list all of the properties of the input button should below in the document. than the actual code for the button itself. It it is present in the head, it will give an error to the effect that document.form1.inputButton is not a valid button. After you press OK on the dialog box, the script runs, giving the output that is listed below, which is a list of all of the properties of the button type of INPUT element.

language scrollHeight isTextEdit currentStyle document onmouseup oncontextmenu isMultiLine clientHeight onrowexit onbeforepaste onactivate scrollLeft lang onmousemove onmove onselectstart parentTextEdit oncontrolselect canHaveHTML onkeypress oncut onrowenter onmousedown onpaste className id onreadystatechange onbeforedeactivate hideFocus dir isContentEditable onkeydown clientWidth onlosecapture parentElement ondrag ondragstart oncellchange recordNumber onfilterchange onrowsinserted ondatasetcomplete ondragenter onblur onresizeend onerrorupdate onbeforecopy ondblclick scopeName onkeyup onresizestart onmouseover onmouseleave outerText innerText onmoveend elementName title offsetWidth onresize contentEditable runtimeStyle filters ondrop onpage onrowsdelete elementUrn offsetLeft clientTop style clientLeft ondatasetchanged canHaveChildren ondeactivate isDisabled onpropertychange ondragover onhelp ondragend onbeforeeditfocus disabled onfocus behaviorUrns accessKey onscroll onbeforecut readyState all sourceIndex onclick scrollTop oncopy tabIndex onbeforeupdate outerHTML innerHTML ondataavailable offsetHeight onmovestart onmouseout scrollWidth offsetTop onmouseenter onlayoutcomplete offsetParent onafterupdate ondragleave children start readOnly firstChild type height alt form onerror hspace maxLength loop onselect lastChild nodeName nodeType width dynsrc attributes childNodes src dataFld previousSibling parentNode checked onabort nodeValue onchange dataFormatAs defaultChecked vrml dataSrc indeterminate onload align lowsrc complete nextSibling vspace size value border status name
You can see that the list is enormous - there are alot of properties associated with an INPUT element. That's it for the for / in loop.

The break Statement

The common break statement is used to "break" out of a loop or switch statement before the condition has been satisfied. That is, the functionality of the loop or switch is broken by the inclusion of the break statement within the loop or switch itself. The break keyword is used almost every time with a label, which tells the browser where it should jump to start execution. Examine the below syntax example which shows the use of break statements and a label within a pair of for loops and a pair of if statements.

labelName:

for (expression)
{
for (expression)
{
if (expression)
break;
if (expression)
break labelName:
}
}


As you can see, the example shows two nested for loops with a pair of if statements nested within the second for loop. At the beginning you can see the labelName keyword that tells the browser that when the break labelName: keywords are encountered, the script should jump to where the label has been stated and start execution again. You can see this break labelName: statement within the second nested if statement. In the first if statement, the break keyword is used alone. This tells the browser to jump out of the statement it is currently in and execute the following code given, if any. There are a few rules to keep in mind. The label must end with a colon, not a semi-colon. Also, when stating the break keyword with a label, the label must end with a colon also. That's it.
The continue Statement

The continue statement is used to tell the browser to jump to the beginning of the given loop and start execution. Labels may be used with the continue statement, and are used in exactly the same way - when encountered, the script will jump to the label point and start executing. There are a few rules to be considered when dealing with the continue statement. These rules apply to where within the various loop structures execution will begin, since the continue statement forces the script to jump to the beginning of the given loop. These rules are as follows for each type of loop structure.

for - The loop begins with the expression in brackets following the for keyword.
while - The loop begins with the expression in brackets following the while keyword.
do / while - The loop begins with the expression in brackets following the while keyword.
- The loop begins with the next property name of the object.

Keeping these rules in mind, examine the following syntax example.

labelName:
for (expression)
{
for (expression)
{
if (expression)
continue;
if (expression)
continue labelName:
}
}


The example shows the use of two nested for loops with two if statements nested within the second for loop. The first if statement shows the use of the continue statement alone, without a label. When encountered, the execution of the script will jump to the top of the loop, in this case the second nested for loop. The expression will again be evaluated and the script will continue. The continue statement with the label will start execution with the loop following the label at the top of the script, executing the first for loop's expression.

The with Statement

The with statement is basically a time saver. It reduces the amount of code that has to be used for a variety of uses. The most common application for the with statement in my experience is for resetting the fields of a form. Why not just use a reset INPUT button you ask? Because some older browsers don't have the rest button as part of the functionality included within the JavaScript engine within that browser. They're still out there, so be wary. Examine the example below which shows the with statement within a function that is called by the form used, when the button is clicked.

<FORM NAME="form1">
<INPUT TYPE="text" NAME="text1">
<INPUT TYPE="text" NAME="text2">
<INPUT TYPE="text" NAME="text3">
<INPUT TYPE="button" NAME="reset1" onClick="reset()">
</FORM>

<SCRIPT LANGUAGE="JavaScript">

reset();

function reset() {
with (document.form1);
{
text1.value = "TEXTBOX1 TEXT";
text1.value = "TEXTBOX2 TEXT";
text1.value = "TEXTBOX3 TEXT";
}
}

</SCRIPT>


The example shows the creation of a form with four elements - three text fields and a button.
The JavaScript Function

The JavaScript function is used to contain a set of commands that can be called upon by the HTML coding you specify within the BODY of your document. Any of the many JavaScript commands may be placed within the function, in any amount and in any degree of complexity which you have a use for. As well, you may specify any number of individual functions within your document. While the JavaScript function is not as powerful as those found in languages like C and C++, there is still enough functionality to achieve most actions the modern web page requires.

As with all JavaScript commands, the JavaScript function must be placed within the opening and closing HTML SCRIPT element, as the following syntax example shows.

<SCRIPT LANGUAGE="JavaScript">

function functionName(optional parameters) {
statements;
}

</SCRIPT>


You can see that the function is fairly straightforward and is relatively easy to use. Calling a function within your document is as easy as simply stating the functionName within an event handler, as the following syntax example shows.

onClick="functionName(optional parameters) ; return true"

Any event handler that applies to the HTML element it is being used with may call the JavaScript function. The "return true" is used to return a value of true to the script, although some scripts may require a "return false" statement, which returns a value of false to the script. Both are acceptable, and the decisions to use both of them are on a case-by-case basis, according to the demands of the script.

All JavaScript functions use the "call by value" method of using arguments, which basically just makes a copy of the argument. The argument is then used for whatever task you've specified and discarded, if not again required by the script. The original argument is not altered in any way. This "call by value" method is the opposite of the "call by reference" method, which alters the original argument directly without making a copy. When the script is finished execution on the argument, the original has been changed. This can lead to problems at a later time, making the script unduly complicated. Because of this, JavaScript does not use the "call by reference" method.

Returning Values to the JavaScript Function

On occasion, you'll have need to return a value to the function you are working with. To do this, you would use the "return" keyword. The value to be returned to the function is simply stated after the return keyword, anywhere within the function. If no value is specified after the return keyword, a value of "undefined" is returned to the function (this is good to know, as some of your JavaScript machinations may require an initial "undefined" value to be returned). This value returned may then be assigned to a variable for later use or used within an expression, as the following syntax example shows.

<SCRIPT LANGUAGE="JavaScript">

function functionName(optional parameters) {
statements;
return variableName = value;
}

</SCRIPT>


You can see that the return keyword has been used within the function to create a variable with a value and return it to the function. Any statements within that function can then use the variable, as the variable is of the Local type. The variable is not available to statements or functions outside of the function it was created in. For a more detailed discussion of Local versus Global Variables, see the JavaScript Tutorial on Variables.
The Function as an Object

While most instances of creating a function will involve the function being created as the document loads into the browser, there is another method that only creates the function when it is called upon by other parts of the script. In using this method, the function is considered to be an object, and is treated as such by the script. Examine the below syntax example of creating a function as an object.

var variableName = new Function(argumentOne, argumentTwo, etc.);

When stating a new instance of the core JavaScript Function object as a variable, the function is treated as an object. The capabilities of the function as an object are less than the other more common method of creating a function. There is no space provided for a statement to be executed on what would be the parameters of the common method of creating a function. There are only a set of arguments available to achieve what it is you set out to do. Use this method when you want to perform simple machinations on a variable that has been created earlier within the script.

Pattern Matching - The RegExp Object

The RegExp object is a Core JavaScript Object. RegExp stands for Regular Expression. The RegExp object was based on the PERL implementation of Regular Expressions. PERL is a very capable and powerful scripting language. To put it simply, the RegExp object is used to find a match to the text you want to find. Various "switches" are used to give you options on how to find the text. On your browser, if you select the "find" option from the menu, you type in a string of text you would like to find, then click OK. The browser uses a Regular Expression to find a match to your text within the web page (or whatever application you are working in - the Regular Expression is very widely used, and in many languages).

With the RegExp object, you may not only find a match to your desired text, but also verify user input for things like valid postal and zip codes, telephone numbers, and account numbers. The RegExp object works by first creating a new instance of the Core RegExp object, then assigning a pattern for the object to match, as in the following syntax example.

var name = new RegExp("String of Text");

The above syntax example creates a new instance of the RegExp object called name which looks for the string String of Text. While this is the most common method of creating a new RegExp object, there is another more shorthanded form, as follows.

var name = /String of Text/;

Placing the String of Text between two forward slashes tells JavaScript that the text, the "pattern", must be applied to the RegExp object. This method is called "Direct Assignment".

Defining Your Search Patterns

As mentioned earlier, there is an extensive set of "switches" used to further refine your search. Used properly and with some creativity, it is almost guaranteed that you'll find a specific match to your search string. The pattern matching characters available to JavaScript are given in the list below.

\w - Find a match to any alphanumeric character within a word
\W - Find a match to any non-word character
\s - Find a match to any whitespace character such as a tab character, newline, carriage return (enter), form feed, or vertical tab.
\d - Find a match to any numeric digit
\D - Find any character that is not a number
[ \b ] - Find a match for a backspace.
. (period) - Find a match for any character except a newline character.
[ ... ] - Match any one character within the square brackets.
[ ^... ] - Match any character not within the square brackets.
[ x-y ] - Match any character between X and Y.
[ ^x-y ] - Match any character not between X and Y
{ x, y } - Match the previous search string at least X times, not to exceed Y times.
{ x, } - Match the previous search string at least X times.
{ x } - Match the previous search string exactly X times.
? - Match the previous search string once or not at all.
+ - Match the previous search string at least once.
* - Match the previous search string any number of times, or not at all
| - Match the expression to the left or the right of the | character.
( ... ) - Group everything inside of the parentheses into one sub-pattern.
\x - Match the same pattern within the last sub-pattern in group X.
^ - Match the beginning of a string or the beginning of a line, in multi-line search string matches.
$ - Match the end of the search string or the end of a line, in multi-line search string matches.
\b - Match the position between a word character and a non-word character.
\B - Match the position that is not between a word character and a non-word character.
Using the above list of options, it is almost a certainty that you'll find the string you are looking for. But this is not all that JavaScript offers. There is also a list of what are called Literal Characters JavaScript uses to make the search for your string easier, less complicated. That list is as follows.

\f - Find a form feed character.
\n - Find a new line character.
\r - Find a carriage return character.
\t - Find a tab character.
\v - Find a vertical tab character.
\/ - Find a forward slash.
\\ - Find a backward slash.
\. - Find a period.
\* - Find an asterisk.
\+ - Find a plus character.
\? - Find a question mark.
\| - Find a horizontal bar.
\( - Find a left parentheses character.
\) - Find a right parentheses character.
\[ - Find a left square bracket character.
\] - Find a right square bracket character.
\{ - Find a left curly brace character.
\} - Find a right curly brace character.
\XXX - Find an ASCII character represented by the octal number \XXX.
\xHH - Find an ASCII character represented by the hexadecimal number \xHH.
\cX - Find a control character represented by \cX.

You can see that most of the conceivable options have been defined for you. The creators of the JavaScript specifications have been very thorough. But there are two more "switches" that are probably the most commonly used of them all. Those two Pattern Attributes are as follows.

\g - This is for a Global Match, and is used to find all possible matches to your search string.
\i - This is for a case-insensitive match.

Workhorses - The Pattern Matching Methods

In working with the RegExp object, you'll become accustomed to using the many methods available to both the RegExp object, and the String object. The String object works hand-in-hand with regular expressions to find the specific match you're looking for. There are four JavaScript Methods within the String object that were designed to aid in the process of matching a pattern. They are as follows.

match(RegExpObject) - This method searches the given string for the pattern defined within RegExpObject, which was created at an earlier point within the script.
replace(RegExpObject, string) - This method searches the given string for a match to the RegExpObject, which was created at an earlier point within the script. If a match is found, the method replaces the matched text with string, given as a parameter to the method.
search(RegExpObject) - This method searches the given string for a match to the RegExpObject, which was created at an earlier point within the script. When found, the method returns the character position of the starting point of the matched RegExpObject within the given searched string.
split(RegExpObject, max - This method searches the given string for a match to the RegExpObject, which was created at an earlier point within the script. The searched string is then "split" wherever there is a match found, up to max splits. The new, splitted strings are then returned by the method within an array. You might have noticed that all of the above String methods required a RegExp object to function. Conversely, all of the RegExp methods require a String object to function. The four RegExp methods available are as follows.
exec(stringObject) - This method searches for a pattern within stringObject, and returns the result.
test(stringObject) - This method searches for a pattern within stringObject. If a match is found, a value of true is returned. If no matches are found, a value of false is returned.
compile(pattern, flag - While this method doesn't use a String object, it should be mentioned here. It is used to compile a list of all of the matches found within the search string by the regular expression. The pattern is a functioning RegExp object, and the flags may be either the \g or the \i Pattern Attributes, or both.
(stringObject) - This method behaves exactly as does the exec(stringObject) method, but in a shorthanded form.
Creating Your RegExp Objects

In the following examples of using the RegExp object, you'll see how versatile and fairly simple the RegExp object is to use. We'll keep things simple until you get a feel for the Object, then up te skill level a bit. You'll be a pro by the end of the day. As the syntax examples earlier in this tutorial show, the actual creation of a regular expression is quite easy. Examine the below working example.

regExpSearch = new RegExp("(this)");

stringToSearch = "The (this) is the string to be searched.";

regExpArray = regExpSearch.exec(stringToSearch);

document.write("The last value in parentheses is : " +RegExp.lastParen);


The example first starts with the creation of a new RegExp object, called regExpSearch. The search is for the word "this" in brackets. Next created is the string to search through, called stringToSearch, with the word "this" in brackets. Next comes another variable which contains the RegExp expression (regExpSearch) and the exec() method, which performs the actual execution of the search. Contained as a condition within the exec() method is the variable representing the string to be searched, stringToSearch. Finally a document.write statement is declared, which uses the lastParen property of the RegExp object to return the last value in parentheses, which is "this". The returned value looks like the following:

The value in parentheses is : this

You can see the power you have at your fingertips when using the RegExp object. Now for something a bit more complicated. Examine the working example below, and study the explanation given.

var stringToSearch = new String("This is the string of text that will be searched");

var theRegExp = /\s\w*/g;

var searchArray = stringToSearch.match(theRegExp);

if (searchArray == null) {
document.write("No matches were found");
} else {
document.write("The following matches were found within the text :
");

for (var n = 0; n < searchArray.length ; n++) {
document.write(searchArray[n] + "
");
}
}


The example is very complicated, but also very functional. The code was started with the creation of a new string called stringToSearch. Next came the regular expression that was named theRegExp. After the declaration of the regular expression, the array the results are to be put in is created, called searchArray. The condition of the array was executed to find a match using the match() method with theRegExp within parentheses as the parameter. An if / else statement was then used to write one message to the screen if a match was found and one if no match was found. If a match is found, then the for statement accesses the searchArray array and displays the contents of the array, each item on a separate line. The output of the above code is shown below:

The following matches were found within the text :

is
the
string
of
text
that
will
be
searched

Working with Forms

Learning to work with and understand the actions of a form is of paramount importance to the online developer. When you first started building your forms using HTML element and attributes, it was an easy thing. Now it gets a bit more complicated, but not much. Using JavaScript to verify the data the user provides within your form is probably the most common use of JavaScript. You may verify that a correct postal or zip code was inputted by the user. You may send an alert when the user doesn't fill in their last name. These things used to be in the domain of CGI scripts, written most commonly in PERL, another of the scripted languages. This had the detritus effect of increasing server load. Increase server load and you get increased costs and complexity. Not good.

Since the creators of the standards for the Internet were professionals who realized this shortcoming, they created JavaScript, which runs on the user computer, decreasing server load. CGI scripts became more efficient and costs were lowered. JavaScript became an accepted standard, now with many versions and revisions. The great, bulky Mainframes were all but eliminated.

There are two ways of submitting the form data on your page to the server - the GET method, and the POST method. Each has its own advanelementes and each has its own shortcomings, as you will see.

The GET Method

The GET method of submitting form data is the most common way of submitting form data, and is the default in most browsers. The information within the form the user has provided is appended to the URL of the server that is to process the form data. The actual URL of the server is separated from the form data by a question mark. You can normally see the GET method in action if you watch the address bar of your browser while submitting information on a site that calls for some form data to be sent to the server. The address bar might look something like the following.

https://www.walkthegeek.com/process.cgi?fieldOne=Accept

The above example shows form data being sent to the www.walkthegeek.com server. The data is to be handled by the CGI script entitled process.cgi. The form data is separated from the CGI script name by a question mark. The "fieldOne" entry after the question mark is the name of the HTML element that the user provided input to. The "accept" is the value the user has selected from the HTML element. The HTML code that would send this information would look like the following.

<FORM ACTION="https://www.walkthegeek.com/process.cgi" METHOD=GET>

<SELECT NAME="fieldOne">
<OPTION VALUE="Accept">I Accept</OPTION>
<OPTION VALUE="Decline">I Do Not Accept</OPTION>
</SELECT>

<INPUT TYPE="button" VALUE="Submit">

</FORM>


In the above code, the FORM element has its ACTION and METHOD attributes set. If you leave out the ACTION attribute, nothing will happen - your form will not be processed. If you leave out the METHOD attribute, the browser will assume you want to use the GET method of form data submission. It is a good programming convention to use the METHOD attribute, even if you want to use the GET method. This prevents any confusion on the part of the browser, as well as speeds things up - the browser won't have to make an informed decision, which takes time. Note also that there is an INPUT element of the "button" type. Recall from the HTML tutorials that in order for a form to be submitted, a button to tell the browser to submit the form must be in place. Last, all form elements must obviously be within the opening and closing HTML FORM element.

The GET method is used when you don't have a lot of information to be sent to the server. The information to be sent to the server is readable by the informed Internet surfer because it appears as text within the address bar. If security isn't of primary importance, use the GET method. If security is required, it is recommended you use the POST method, which operates slightly different, as you will see.

The POST Method

The POST method of submitting form data to a server is of a higher level of security simply because the users can't see what is being submitted to the server. The form data is submitted within the body of the http request to the server. Security considerations aside, the POST method is used to send large amounts of form data to the server, amounts which the GET method will not be able to handle. The POST method isn't used much, as the amount of information required to overload the GET method is actually quite large.

When the browser sends a request to the web server for information such as a web page, the information sent to the server is of two parts - the head and the body. The method of submitting the form data to the server is almost the same as a simple page request. The browser substitutes the URL of the page the user might want with the form data the user has provided as the body of the request. The server catches this, and processes the data according to the CGI script given within the ACTION attribute of the FORM element.

Constructing your HTML form is exactly the same as if you were using the GET method. The form contents must be within the opening and closing HTML FORM element, and some sort of INPUT button must be provided to tell the browser when to input the form data.
Accessing Form Data Properties

In order to verify the information the user has entered, you must be able to access the information. To this end, the creators of JavaScript have provided two major means of accessing and working with form data - the Form Array, which is a property of the document object, and the Elements array, which is an array within the Form object. Both are used quite extensively to validate user input and perform some simple processing tasks on the client side.

The forms array of the document object and the elements array of the forms object work the same as any other array. The forms are listed within the array in the order they appear within the BODY of the HTML document. Each is accessed by its index number within this array, as the following syntax example shows.

document.forms[indexNumber].formProperty

OR

document.elements[indexNumber].formProperty

The above example shows the accessing of a form within the current document. The property to be accessed within the form is represented by the formProperty. Simple. Note that the array index is zero based, meaning the count of the items within the array start at the number zero and go up from there. forms[0] would be the first form within the document, forms[1] would be the second, and so on. Consult the JavaScript Language Reference to find a listing and in depth discussion on each of the properties of the forms array.

It may be easier when you have many forms in one document to access the properties of the forms via the form names. The name of a form is specified through the use of the HTML NAME attribute of the FORM element. Examine the syntax example below.

document.elementName.formProperty.value

The above syntax example shows the accessing of a property via the elementName name of the element, in this case a form element. The value keyword given after the property tells the browser that the value given or selected by the user is to be used as the value of the statement. The value is usually the product of the user either typing something within an INPUT element's text field or the choosing of an option or options through the use of radio buttons, checkboxes, or SELECT / OPTION lists. In the case of the text field, the value becomes the typed text. In the case of the radio buttons, checkboxes, and SELECT / OPTION lists, the value is specified by the HTML VALUE attribute given within the pertinent element by you, the page author.

Dynamic HTML is the implementation of four language specifications - HTML, CSS, DOM, and JavaScript. Each has its own place within the modern document. Each covers one or more parts pertaining to the presentation of your completed document. In a nutshell HTML is for object placement, CSS is for coloring and formatting, DOM is the link between HTML / CSS and JavaScript, and JavaScript is the workhorse of your document. The below sections delve into this symbiotic relationship in more detail.

The HTML In A Document

In the beginning, there was only HTML with which to build your pages. Many pages are implemented through the use of HTML only, although most of them don't quite pop. Adding the other parts of Dynamic HTML will add to the functionality and make your page look great. In implementing Dynamic HTML in your pages, HTML is the part you use to include objects into your document, define initial colors and the basic look of your page. The rest of the four constituent parts of Dynamic HTML - CSS, DOM, and JavaScript - are more to provide functionality and a 'feel' for your page. I'd recommend starting your page design with HTML only. This is because HTML is used to (as stated earlier) define the look of your page, as well as specifying the inclusion of any type of content you'll be providing. Design your graphics and place them in their proper places within the page, keeping in mind that you may add functionality and dynamic content at a later selemente in the evolution of your page.

The CSS In A Document

When the CSS-1 specification was first defined, it was heralded as a great invention, which will revolutionize the way web documents are created. There was much hype, and it was well founded. The implementation of Cascading Style Sheets has revolutionized the way web pages are created. It is an amazing set of tools that affect almost every aspect of the web page. With it you can specify, using only one file, all of the guidelines for the presentation of your web site. I'm talking about external style sheets, of course, and they really are an amazing tool to work with. Used right, the entire look and feel of any site, large or small, may be altered and tinkered with until it fits with what you, the author, first envisioned when you created your first document. By altering that one file, the entire format of a web site may be changed. Previous to CSS, each individual HTML document would have to have been altered one at a time, by hand - a horribly tedious and tremendously boring job.

With CSS you can specify everything from border widths to colors and textual effects such as 3D shading to create a raised effect for borders and containers. Text headings can be defined and implemented with one easy to use and understand attribute (the ID or CLASS attributes). Using the external style sheet, you may make your distinctive look span across your entire web site.
The DOM In A Document

The specifications of the Document Object Model are the link between the capabilities of HTML and CSS (which work hand in hand) and the advanced capabilities of the JavaScript scripting engine. Every HTML element that can be defined is represented within the Document Object Model, the representation of which can be accessed and therefore changed using a JavaScript function or statement. As I've mentioned before, the implementation of DOM within the two major browsers (Microsoft's Internet Explorer and Netscape's Navigator) differ greatly. Netscape has almost no support for DOM except for form controls and some basic textual and color formatting. The so-called 'higher' DOM capabilities are still a mystery to Navigator. These higher capabilities are what make DOM so great to use. It is the brains behind DHTML. That is, it is what is defined when you specify what you want to change. Its hierarchical tree is logical and ordered, and easy to understand. Using dotted notation (much like an IP address), it is possible to access every element of the page you are working with in a timely, ordered manner. This is what makes DOM so great and therefore so widely used.

The JavaScript In A Document

JavaScript and its huge array of capabilities is the workhorse of DHTML. It is used to encapsulate the DOM statements for the page to use. You may define JavaScript functions or statements and incorporate the DOM commands into them. Navigator uses JavaScript almost exclusively to manipulate or "make dynamic" the content of its pages. It is possible to achieve most of the effects in JavaScript that DOM has to offer, though in a very complex and bandwidth heavy form. That is, to achieve one effect in JavaScript that DOM will do requires extensive JavaScript programming, adding complexity and therefore download time to your documents. Most people with even the slightest sense of practicality will see this as a huge waste of time and effort. Most of the time the effect is left out when the developer realizes the depth of programming which is involved to achieve even the slightest dynamic effect.

JavaScript can be used as a reporting tool, a container for DOM statements, and a great source for advanced programming functions, most of which pertain to data checking and confirmation. That is, JavaScript can be used on the client side (in the user's browser) to confirm that data being sent to a CGI script on a server is in the right format and contains no strange characters or obvious user mistakes such as an invalid email address or postal code. Using JavaScript in this way, the load on the server can be reduced dramatically, saving time and bandwidth, and therefore money.

Changing Colors

Changing colors is the most basic of all of the dynamic aspects of Dynamic HTML. In Internet Explorer, almost every color that can be set can be changed dynamically with the implementation of Dynamic HTML. You can change anything: borders, text, backgrounds, margins, and padding. You can make anything cycle through colors either randomly or to a set number of colors. Anything your imagination can dream up (and your skill level accommodate) can be done when it comes to color changing.

There are a couple of ways colors may be changed. There is the "DOM statement as an Event Handler Value" method or the "DOM Statement in a JavaScript function" statement. Almost all of the time the thing or things you'd like to change the color of must be identified with either the CLASS attribute (for groups of things) or the ID attribute (for single things). Each works the same way but applies the change to a different place or places. You can see the major difference here - the CLASS attribute is used to identify groups of things, and the ID attribute is used to identify individual things. Of the two, the ID attribute is used more often. It simply provides a larger measure of control than does the CLASS attribute.

The DOM statement as an Event Handler Value

Using a DOM statement in an event handler is a good way to assign an action to an element, and control when it is triggered. You have about forty different event handlers to choose from, so you'll not be hard pressed to think up a creative way to accommodate the vision you have for your web page. The event handler exists for just about any user driven action that can take place within a modern web page. While some event handlers only work with a few or even just one HTML element, there are many that work for almost all of the available HTML elements. the onClick event handler, for instance, is pretty global in its use - it works with everything. Most of the "onMouseXXXX" (onMouseUp, onMouseDown, onMouseOver, etc.) event handlers work with almost every element as well.

To begin to set your page up for a color change, you first have to create the thing that is to be colored. We'll start with a simple line of text. It will originally be black, but when the mouse pointer passes over it, it turns red. Simple.

<SPAN ID="changeIt">
<FONT SIZE="3" COLOR="black" onMouseOver="document.all.changeIt.style.color='red' ;
return true">This is a line of text</FONT>
</SPAN>


You see that it is a fairly simple thing to do, if done right. We started with a SPAN element which is assigned the ID of "changeIt". The opening and closing SPAN element have the FONT element nested within. The FONT element, therefore, has the "changeIt" identity assigned to it also. The gist of the example is in the onMouseOver event handler. You see a DOM statement as the value of the event handler. Before I explain the workings of the DOM statement, it is essential that I first explain a rule which we've just broken slightly. Notice that the value of "red" is within single quotes. This is because the DOM statement is the value of the event handler. The value of an event handler must be enclosed within double quotes for compatibility with older browsers. DOM provides a bit of lee way with single and double quotes, but HTML event handlers do not. Hence the use of the single quote.
Since the FONT element has been assigned the "changeIt" identity, we may use it in a DOM statement utilizing the "style" object. The DOM statement first starts with the "document" object, which represents the current document since there was no window name stated before it. The "all" object is used, and tells the browser that the following command is to be executed within the entire document ("all" of the document). Next comes the value of the ID attribute, which is the name of the SPAN element - "changeIt". This can be anything, really, including all alphanumeric characters. Since we've now told the browser that the command is to be within the current page for all instances of the "changeIt" ID attribute, we now have to tell the browser what to do. This is accomplished with the "style" object, which tells the browser that an instance of the style object (which is generated for every element on the page) will be accessed. Next comes the "color" property with the value of "red", which tells the browser to change the color to the named color, red. This DOM statement, with the ID attribute and the onMouseOver event handler tells the browser what to do (the DOM statement), where to do it (the ID attribute), and when to do it (the onMouseOver event handler). Sounds complicated, but it's actually pretty easy to do once you get a feel for it.

Now that you know how to change a color using a DOM statement as an event handler value, we can take this one step further to achieve a result which you've probably already noticed if you tried the example on a working HTML document. You'll notice that the color of the text is originally black and then changes to red when the mouse passes over it, but in a real world situation, you normally wouldn't want the text to just change to red and stay there. Color changes are usually to accentuate when the mouse pointer passes over something. This tells the user that something of importance is there. It also tells the user which link is selected - a handy feature in a long and tight list of links. So to change the color back to black, simply add another DOM statement with the opposite event handler to the original onMouseOver event handler with a value of the named color "black". This opposite is the onMouseOut event handler. Examine the new addition to the above statement:

<SPAN ID="changeIt">
<FONT SIZE="3" COLOR="black"
onMouseOver="document.all.changeIt.style.color='red' ; return true"
onMouseOut="document.all.changeIt.style.color='black' ; return true"
>This is a line of text</FONT>
</SPAN>


The new addition to the statement, in my opinion, completes the functionality intended by the makers of DOM. It changes the text color to red when the mouse passes over it, then back to black when the mouse moves away from over top of it. The onMouseOut event handler uses the same approach as does the onMouseOver event handler. The only thing that has changed is the value (the named color, black) of the "color" property of the "style" object. This easy to use implementation of DOM is the most widespread use you'll find in todayís web pages. It is simple and requires fairly little space - you won't be typing all day and receiving JavaScript error messages when your page loads into an older browser, as it invariably would if you used JavaScript only to infer the color change.

The DOM Statement in a JavaScript function

Another alternative to the above color change is to put the DOM statement as the argument of a JavaScript function. The onMouseOver and onMouseOut event handlers are still used, but with a twist. The JavaScript function is called instead of the DOM statement itself. The changing of the color to red requires a function, as does the changing of the text back to black. Examine the below JavaScript code.

<SCRIPT LANGUAGE="JavaScript">

function changeIt() {
document.all.changeIt.style.color='red' ;
}

function changeItBack() {
document.all.changeIt.style.color='black' ;
}

</SCRIPT>


The above snippet of code is placed within the HEAD of the document. Keeping this code in mind, the code within the BODY of the document would look like the following:

<SPAN ID="changeIt">
<FONT SIZE="3" COLOR="black"
onMouseOver="changeIt() ; return true"
onMouseOut="changeItBack() ; return true"
>This is a line of text</FONT>
</SPAN>


You can see that the DOM statement has been left out of the event handlers and is replaced with the JavaScript function name. The coding used here is more to illustrate the use of DOM within a function versus DOM as an event handler value. You would normally use the "DOM as an Event Handler Value" unless you're using the CLASS attribute instead of individual ID attributes. Remember that the CLASS attribute, in this case, would change the color of all of the elements that contain the "changeIt" identification - the CLASS attribute is for groups of elements.

Now that you have a grasp of how to implement DOM in a dynamic way, you're ready to have dynamically changing colors in all of your documents, for any page element you wish. simply assign the ID (or Class) attribute to the element you wish to change, and change the object property ("color", in the above examples) to reflect the property you wish to change. A full list of available properties is listed within the Document Object Model Reference for the style object.
Changing Text Properties

In the course of your creation of a dynamite web page, you might have need to change the properties of the text you are working with. By far the most powerful specification for the manipulation of text is CSS. Huge arrays of text formatting options are available to specify exactly what the rendered text you are working with will be displayed as. Examine the below list of text formatting categories available to CSS.

Letter Spacing - Used to define the spacing between the individual letters of your text.
Line Height - Used to define the height of the line in which your text is to be displayed.
Text Align - Used for text alignment purposes such as aligned left, right, centered, or justified.
Text Decoration - Used to define special effects to text such as blinking and underlining.
Text Indention - Used to define the indentation format of the paragraphs of text with which you are working.
Text Transformation - Used to define what format the text is to be displayed in, such as all capitals or lowercase.
Vertical Alignment - Used to define the alignment of your text in relation to the bottom of the line of text. Examples are subscripted and superscripted text.
Word Spacing - Used to define the spacing between the individual words of your text.
Font Family - Used to define what font is to be used to display your text.
Font Size - Used to define the size of the font to be used to display your text.
Font Style - Used to define the style to be used to display your text. Examples are italicized or oblique.
Font Variant - Used to define what variant of the font is to be displayed. Examples are all small caps or all lowercase.
Font Weight - Used to define the "weight" of the font used. Measurements are multiples of 100 through to nine hundred.

The above categories are used solely to manipulate the text of your page. Every aspect of the above list may be changed dynamically through the use of a combination of DOM and HTML Event Handlers, using exactly of the same methods you would use to change colors, namely with the "style" object. A full list of options and syntax for each category is available in the Language Reference section, CSS Text Properties.

Not only are there text formatting options, but positioning options as well. CSS and HTML, working together, provide a host of additional specifications to play with, such as borders, padding, and margins. Each has its own set of properties that can be used to implement your desired look. A word should first be given on exactly what is meant by the terms borders, margins, and especially padding. While borders and margins are very intuitive concepts, padding is a bit different. Examine the graphic given below, which outlines the relationship between the border area, margin area, and padding area.

In the figure above, you'll notice that, of course, the box has two sets of sides - the top and bottom, and the left and right. Although you can state a margin or padding or border value for each individual side, the most common practice is to state just one value which will be used on all of the four sides. Keeping this in mind, in order for you to fit an element that is say 200 pixels wide in a 210 pixel wide space, a padding not of ten should be stated, but of five - the value of five will be applied to both sides of the element space, resulting in a total padding area of ten.

When using measurements with CSS, you'll no doubt find it useful to know the full list of measurement options available to you. Peruse the below list of measurement options available to almost all of the CSS options that require a measurement.

mm - millimeters.
cm - centimeters.
in - inches.
pt - points, which is a way of measuring the font size. One point is 1/72 (one seventy-second) of an inch.
pc - picas, which is yet another way of measuring font size. One pica is equal to 12 points.
px - pixels, which is one screen element. The display you're looking at is comprised of thousands of individual dots, each of which can change in color and luminosity to achieve the desired image. Each of these dots are referred to as a pixel.
ex - x-height settings, which is the height of the font's lower case letter 'x'.
em - em setting. One em is equivalent to the width of a capital "M" in the chosen font.

Millimeters, centimeters, inches, points, and picas are considered to be absolute lengths because you're specifying the exact size of the value. Relative units such as em and ex are interpreted as references to the parent font size. Using the percenelemente method sets the length for the distance between the element (the 'thing') and the inside of the border, padding, or margin as a percenelemente of that element's dimensions.
Changing Your Text Properties

As mentioned earlier, you may use the DOM "style" object to change your text properties on the fly or according to user preference. The syntax for the changing of these text properties is exactly the same for changing colors, as follows.

window.document.all.elementID.style.property = "value"

As you can see, the properties can be changed dynamically in another window by specifying a window name before the document.all portion of the statement. The elementID is a section of your HTML document that has been defined through the use of an ID or CLASS attribute within a element. The property must be a valid property pertaining to the contents of the element that has the ID or CLASS attributes stated. The "value" must be enclosed within double quotes, and must be a valid value of the stated property.

Examine the below example, which changes the letter spacing of the text within the SPAN element when the mouse passes over the text itself.

This is the Example Text

You can see that it is a nifty effect you might find a use for. Examine the code below to see how it was done.

<SPAN ID="textBlock"
onMouseOver = "document.all.textBlock.style.letterSpacing = '1em' ; return true"
onMouseOut = "document.all.textBlock.style.letterSpacing = '0em' ; return true">
This is the Example Text
</SPAN>


You can see from the example that there were two separate statements used - one to make the change, and one to change it back to the normal appearance. From the above list of measurement options available to CSS properties, I've selected the "EM" measurement. Notice that the value of "1em" and "0em" are within single quotes, breaking one of the rules set out in the DOM specifications. This is because the DOM statement itself is within the double quotes that define the value of the event handler itself. Single quotes for the value of the DOM statement in this situation are allowed. Notice also that I stated the ID attribute within the same element as the DOM statement. This is also allowed, although older versions of Netscape don't really like it.

You may substitute any valid property for the "letterSpacing" property. See the DOM and CSS Language Reference to see what is available to you. With a bit of imagination, you can create some very interesting effects.

Now on to padding, margins, and borders. From the above graphic, you can see that there is no guesswork in the placement of your padding, margin, and border areas. This makes it possible to have a very large degree of control in the flow and placement of your text, and the surrounding images, if any. There are many options available for each of the three, as the following list shows.

Border Properties
Border Bottom Width
Border Bottom
Border Color
Border Left Width
Border Left
Border Right Width
Border Right
Border Style
Border Top Width
Border Top
Border Width
Border Margin Properties
Margin Bottom
Margin Left
Margin Right
Margin Top
Margin Padding Properties
Padding Bottom
Padding Left
Padding Right
Padding Top
Padding Properties

From perusing the above list, you can see that it's quite an impressive list of options. Each are accessed as a property of the "style" object, the use of which is universal to all of its 140 - plus properties. Use them well.
Swapping Images

If you've surfed the 'net, then you've seen those cute little buttons that seem to "depress" when your mouse pointer passes over them. This is because an image is swapped for the original, "unpressed" image that gives the impression that a 3D button has been depressed. This swapping of images is a widely used method to attract the user's attention to a specific area of your page. It looks good too, if done right.

Image swap is accomplished in one of two ways - through the use of the elementID.src statement, and through the accessing of an array that contains the images you wish to display and swap. Of the two, the first is easier to implement, though it has some drawbacks. We'll concentrate on the first method first.

Swapping Images with the elementID.src Method

Basically, you would start with the building of a complete HTML document, with the images you wish to use as buttons in the places you wish them to be. The "depressed" button image must be complete and ready to go, and it is recommended it be exactly the same size as the original, unpressed button. Examine the code below, which swaps image1.gif with image2.gif. It may appear anywhere you wish it to within your web page.

<A HREF="pageTwo.html"
onMouseOver = "imageButton.src = 'image2.gif' ; return true"
onMouseOut = "imageButton.src = 'image1.gif' ; return true">
<IMG SRC="image1.gif" NAME="imageButton">
</A>


You can see that the elementID.src method is very easy to implement. It can be used to swap any two images. The example shows the link to pageTwo.html. The original image to be used for the link is image1.gif, and is initially defined through the use of an IMG element. Notice that the IMG element has been named with the NAME attribute. This link between the first image and the second image, image2.gif. Since the onMouseOver event handler has been used, the event will be triggered when the user places the mouse pointer over the image. When the pointer is over the image, image1.gif is swapped with image2.gif, as per the "imageButton.src = image2.gif" value of the event handler. When the user moves the mouse away from the image, the onMouseOut event handler is triggered, which switches from image2.gif back to image1.gif as per the "imageButton.src = image1.gif" value of the onMouseOut event handler. Simple.

There are some drawbacks to this method, however. The most notable drawback is that the image2.gif graphic is only downloaded from the server when the user passes the mouse pointer over the image link and triggers the event. This can lead to a pause before the image2.gif graphic is displayed, as it takes time to download. If the image is a large one, the user may have lost interest and moved on before the image has had a chance to swap. On the other hand, if the user doesn't trigger any image swapping, the image doesn't have to be downloaded at all, saving some of that expensive bandwidth. This is not as great as it sounds - the amount of coding for each image swap is large, so any bandwidth savings are limited.
Swapping Images from a Pre-Loaded Array

The other way to swap your images is through the use of a JavaScript array. The array is loaded with the URL's of the images to be used for the buttons. OnMouseOver and onMouseOut event handlers are still used to trigger each image swap, but you need only specify the proper list item from the array. This reduces download time because of its low overhead. Another advanelemente to this method is that the images are pre-loaded into the browser's memory, making image swaps quick and clean, with no lag time at all. While the user is initially reading what your site has to offer, the rest of the images are downloaded. This is transparent to the user - they don't know that they're still downloading images which will be used for the "depressed" button. Examine the code below. It looks complicated, but the explanation following it will make it make sense.

<SCRIPT LANGUAGE="JavaScript">
if (document.images) {
var upButton = new Array()
upButton[0] = new image(25, 25)
upButton[0].src = "image1.gif"
upButton[1] = new image(25, 25)
upButton[1].src = "image3.gif"
upButton[2] = new image(25, 25)
upButton[2].src = "image5.gif"
upButton[3] = new image(25, 25)
upButton[3].src = "image7.gif"

var downButton = new Array()
downButton[0] = new image(25, 25)
downButton[0].src = "image2.gif"
downButton[1] = new image(25, 25)
downButton[1].src = "image4.gif"
downButton[2] = new image(25, 25)
downButton[2].src = "image6.gif"
downButton[3] = new image(25, 25)
downButton[3].src = "image8.gif"
</SCRIPT>


This chunk of code is usually placed in the HEAD of the document, though it can be placed anywhere within your page. This is the array that now contains the images to be used in the swap. The images in the "upButton" array are the images the user initially sees as the page loads. The "downButton" images are the ones the user sees when the mouse pointer moves over the image, triggering the image swap. The below chunk of HTML code is placed within your page.

<A HREF="page2.html"
onMouseOver="downButton(0)"
onMouseOut="upButton(0)">
</A>
<A HREF="page3.html"
onMouseOver="downButton(1)"
onMouseOut="upButton(1)">
</A>
<A HREF="page4.html"
onMouseOver="downButton(2)"
onMouseOut="upButton(2)">
</A>
<A HREF="page5.html"
onMouseOver="downButton(3)"
onMouseOut="upButton(3)">
</A>


The four linked images are represented by the above chunk of HTML code. Notice that the array starts with the number zero, as is the norm within most programming languages, JavaScript included. For brevity's sake, I'll just explain what the first set of event handlers does - they all work in the same way. The onMouseOver event handler loads the image that is in position "0" within the downButton array when the mouse is over the image. The onMouseOut event handler loads the image that is in position "0" within the upButton array. See? Simple.

You can work out that the odd numbered images within the array are the down images and the even numbered images within the array are the up images. It is a convention that might be a good idea to adopt and make your own. The main plus to this method is that the images are preloaded and ready to go - no need to wait for the image to download before it is displayed for the swap. This method is compatible with almost every version of every browser made to date, so it's a good method to use.
Writing Content to Another Window

When you reach the level of expertise and depth with DHTML that requires the use of a data base to perform a function such as enforcing user preferences and content specifications, you'll no doubt have a need to write some pertanent content to another window or frame. Both are accomplished in the same manner, with only the name of the window or frame being the variable part of your expressions. This tutorial will walk you through writing content to a window called "content1". All of the steps required to perform this write are given in the example script and HTML, as well as in the subsequent discussion which follows. I hope you find it useful.

Writing Content via JavaScript

Basically, writing content to another window involves just a few steps - the content must be assembled and a new window named and opened. A writing stream to the window must be opened. The content is written, and then the writing stream is closed. The below example of writing content to another window doesn't involve the use of cookies or data from a database. It was created to give you an idea of what is involved. We found that the explanation of accessing a hypothetical database and its related cookies was just too complicated to be in the first lesson. Examine the example.

1. <SCRIPT LANGUAGE="JavaScript">
2. var content1;
3. var oldContent1;
4. function openWindow() {
5. content1 = window.open("", "sub", "status, height=400, width=400");
6. if (!content1.opener) {
7. content1.opener = window;
8. }
9. setTimeOut("writeContent()", 250);
10. if (!oldContent1) {
11. content1.focus();
12. }
13. }
14. function writeContent() {
15. var newContent = "<HTML><HEAD><TITLE>New Content Window</TITLE></HEAD>\n";
16. newContent = "<BODY BGCOLOR='lightblue'>\n<CENTER><H4 COLOR='blue'>This is the New
Window's Dynamic Content</H4></CENTER>\n";
17. newContent = "</BODY>\n</HTML>\n";
18. content1.document.write(newContent);
19. content1.document.close();
20. }
21. </SCRIPT>


The above script looks much more complicated than it actually is. We'll go through it line by line, according to the line numbers given. You of course wouldn't include the line numbers in the operating script.

Lines 1 and 21

The opening and closing <SCRIPT> element are essential to any script located anywhere within the document. Notice the LANGUAGE attribute. Leaving the version of JavaScript out of the value tells the browser to use the most recent version of the JavaScript scripting engine. All JavaScript commands and statements must be within the opening and closing <SCRIPT> element.

Lines 2 and 3

These lines are the variables that will be used within the two JavaScript functions. Since they are stated outside of any function, they are considered Global Variables that can be used by all JavaScript functions that are within the current page or within external JavaScript libraries that are linked to the current page.

Line 4

On these lines are the creation of new JavaScript functions, named openWindow(). The openWindow() function is of course used to open the window (among other things - you'll see).

Line 5

This line is where the newly opened window is named, through the use of the "content1 = window.open("", "sub", "status, height=400, width=400");" statement. The statement uses the window.open method. Because of the "content1 = " part of the statement is there, the window is now called "content1". Within the brackets of the open() method are the parameters of the open method. The first is the pair of double quotes (which is empty), which is normally used to specify the URL of the HTML document to be used within the newly opened window. Because we aren't using an HTML document for the window content, the pair of quotes are left empty. The second is the type of window to be created - a "sub" window. Next comes the "status" keyword, which tells the browser to display the status bar at the bottom of the new window. The HEIGHT and WIDTH dimensions, which are both 400, tell the browser what size of window to open. For more options pertaining to the open() method, consult the DOM and JavaScript Language Reference.

Line 6, 7, and 8

Line 6 is for older versions of Netscape's Navigator, namely the version 2 browser which doesn't have an automatic opener - the command must be repeated, as shown on line7. Line 8 is the closing curly brace for the "if" statement.

Line 9, 10, 11, 12, and 13

The new window that was just opened takes a while to initiate in early versions of Internet Explorer, namely the version 3 browser. To accommodate this, the window is delayed from opening for 250 milliseconds. The new window, now opened (after 250 milliseconds) is made the focused object on the screen due to the content1.focus() statement. The lines 12 and 13 are merely the closing curly braces for first the "if" statement, then the entire openWindow() function.

Line 14

On these lines are the creation of new JavaScript functions, named writeContent(). The writeContent() function is used to write your new content to the window, as you'll see.
Line 15, 16, and 17

Line 15 is the first declaration of the Local Variable called "newContent". It contains the content that will be written to the window that was opened with the openWindow() function. Notice that the content is in HTML format - the new window is technically an HTML document that you're filling with this function. The HTML coding must be valid, following all of the rules as would a normal HTML document.

Lines 18, 19, and 20

Line 18 opens the writing stream to the newly opened window, content1. The statement tells the browser to write the content that is within the newContent variable defined on the higher lines of code (Lines 15, 16, and 17). Line 19 then utilizes the "content1.document.close()" statement to close the writing stream to content1. Line 20 is the closing curly brace for the openWindow() function.