|
| 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.
- Represents a backspace - the pressing of the "backspace" key.
- Represents a form feed, which is a function of your printer.
- Represents a new line. The characters following will be placed on a new line.
- Represents a carriage return - the pressing of the "enter" key.
- 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.
XXXX - 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
[ ] - 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.
 | | | |