COMPLETE COURSE IN JAVA-SCRIPT

 

                                       DAVID P.FERGUSON

 

 

 

 

 

JavaScript - What is it?

JavaScript is a language that works with HTML to enhance web pages and make them more interactive. It allows a web designer to swap images, create windows on-the-fly, check form fields, and more.

Remember that JavaScript is not Java. Java was created by Sun Microsystems to be a robust programming language. It is a compiled language whose programs can be attached to web pages in the form of applets or used in stand-alone applications. JavaScript, on the other hand, was created by Netscape. It is a simpler language than Java. It is not compiled (like HTML code) and it is generally embedded into HTML code itself.

JavaScript in not JScript either. JScript is Microsoft's equivalent of JavaScript. Much of the code is the same and both are identified by the language="javascript". However, JavaScript and JScript are not identical. Each of these languages has the same basic qualities, but their higher end functionality differs.

 

 

JavaScript: Getting Started

What is needed?

Very little is needed to create JavaScript. Like HTML the only thing needed to create JavaScript code is a simple text editor (like Notepad) and the only thing needed to view it is a web browser that is JavaScript enabled (like Netscape 2.0 and above or Internet Explorer 3.0 and above). Besides software, basic HTML knowledge is needed. It is good to know some of the more advanced HTML like the <FORM> tags and all its subparts, but it is not required.


What are some of the basics?
The JavaScript code is generally embedded into HTML code. It is usually placed between the
<HEAD> and the </HEAD> tags, but it can also be placed in the body of the web page (between the <BODY> and </BODY> tags).

The JavaScript code is placed between the <SCRIPT LANGUAGE="JAVASCRIPT"> and the </SCRIPT> tags. Since some web browsers are not JavaScript enabled the tags <!-- and //--> are used around the JavaScript code to hide it (as you can see these tags are just the HTML comment tags with an added "//" before the end comment tag).

Like HTML, JavaScript has its own comment codes. There are two types:

// this is the first, which is a one-line comment
/* and this is the second,
   which is a block
   comment */

Here is what we have so far:

<HTML>
<HEAD><TITLE>a title</TITLE>
<SCRIPT LANGUAGE="JAVASCRIPT">
<!-- hide the code from non-JavaScript enabled browsers
     //a comment to describe the following code
     . . .the JavaScript code
// stop hiding -->
</SCRIPT>
</HEAD>
. . .

It is important to note that JavaScript is case sensitive. That means that the case of the letters of a command, a variable, and a function matter. That is to say, the "if" statement is not the same as the "IF" statement.

When you work through this tutorial you will come across a number of examples of JavaScript. These cannot jump out and bite you (at least, not yet), so don't be afraid to give them a try. Go ahead and copy the code into a test HTML document add see what you can do with it.

As JavaScript cannot really jump out and harm you in the physical sense, it cannot harm you in the digital sense either. JavaScript is not as powerful as the more robust languages like Java or C++, so don't be afraid of accidentally killing you system with a rogue JavaScript script.

Also, it is beyond the scope of this tutorial to show you everything there is to know about JavaScript. A good way to keep your knowledge of JavaScript growing is to see how other web designers use JavaScript. If you see something new and cool that you do not know how to do, then take a look at the code and see if you can recreate similar effects. Play around with the language, have fun with it.

Now that that is all said and done, lets start learning some JavaScript!

 

 

 

JavaScript: Intro to Variables and Functions

Let us have a look at one thing that JavaScript can do. Go ahead and

If you pushed the above button, then you just saw a JavaScript alert box. Here is the code:

<html>
<head><title>The Title</title>
<script language="javascript">
<!-- begin hiding
      //this function will run the JavaScript alert
      //box and display the given text when called.
            function MsgBox()
           {
                  var text = "Hello World!";
                  alert(text);
            }
// end of hiding -->
</script>
</head>

<body>
<form>
      <input type=button name=b1 value="push me" onClick="MsgBox()">
</form>
</body>
</html>

The first boldfaced line has function MsgBox(). A function is basically a mini program that will run a block of commands when called. All the code that the function is to execute must be placed within the { and the }.

Function names must follow a certain convention. The names must start with a letter or an underscore, numbers can then follow. For example, _hello1() would be a valid name, but 1_hello() name would not. Also, function names must be followed with ( and ). With MsgBox(), the parenthesis are left blank, but if needed the function can be given various parameters. We will use some parameters later on.

Next, you will notice the line var text = "Hello World!";. This, you may have guessed, is a variable. All variables in JavaScript are of the generic type var, even if you intend the variable to hold only integers or only strings. It is not needed to declare a variable with var, but it is a good practice to do it any way. It provides clarity to show when a variable was started, or first created. Also, if a variable is undefined and not declared using var a runtime error message will be displayed. If the variable is declared with var and not defined, the error message will not be displayed, but the variable will hold an undefined value.

Naming variables follows the same conventions as function names. A variable's name can start with a letter or an underscore. After this, numbers can be used in the name.

A variable's type is defined when its value is set. That is to say, the variable text is defined to be a string when it is set to equal the string "Hello World!" When defining a variable to be a string, both the single quotes and the double quotes are valid. text = "Hello World!" could be rewritten to be text = 'Hello World!'. To define a variable to be a number, simply set the variable to a number without the quotation marks.

In JavaScript variables are allowed to change types. For instance, you could have an all-purpose, temporary variable called temp. This variable could be declared as a string and then later on can then be changed to an integer:

var temp = "Hello World!";
temp = 144;

Next is the line alert(text);. The alert command (which in its self is like a function that takes one parameter) is called to create an alert box and print the contents of text, which is the string "Hello World!" The "Hello World!" string could have been placed within the parentheses of the alert command, bypassing the variable all together.

As you can see, a semicolon follows both the variable declaration and the alertcall are followed by a semicolon. The semicolon tells the browser that that line of code is done and so each line of JavaScript must end this way.

Further on down, you will see that in the body there is a <form>. As you may have guessed, this form creates the button you pushed earlier. When the button was pushed a JavaScript event occurred, which was a Click. I used the onClick event handler to respond to the Click event of the button. When the Click occurred, the event handler called the MsgBox() function, which in turn called the alert command.

 

 

JavaScript: More on Variables

JavaScript variables can hold three basic types. These types are numbers (both integers and floating-point), strings, and Boolean values. Boolean variables can only hold either true or false and cannot really be manipulated. Numbers and strings, on the other hand, have much more versatility than just being assigned to values and being printed. Here is what we will be looking at:


Undefined Variables:

When you declare a variable without setting a value to it, then the variable is assigned the value of undefined (Note: the variable must be declared with var). Here is an example:

var someVar;

A variable cannot be directly compared for undefined, but it does hold a false value. That is, if the variable someVar were tested with if(someVar) then someVar would return false. You will see more on the if statement later on. It is important to realize (and again, this will be covered later) the number zero (0) and an empty string ("" or '') will also return a false value.

 

JavaScript: More on Variables - Numbers


Floating-Point and Integer Numbers:

Floating-point numbers can consist of several parts. These are:

The exponential part is expressed by an "e" or an "E" followed by an integer, which can be signed (with "+" or "-"). A floating-point number must have a decimal number followed by a decimal point or an exponential. These are valid floating-point numbers:

3.123214
-3e-12323
.1E121

Integers can be given in decimal (base 10), hexadecimal (base 16), and octal (base 8). An integer with a leading zero is considered an octal number and so only the digits 0-7 will be valid. To represent a hexadecimal number the integer must have a leading 0x (or 0X). The valid digits for a hexadecimal number are 0-9 and a-f (or A-F). The following are valid integers:

-234 //decimal
234 //decimal
0142 //octal
0xaf0012 //hexadecimal


Numeric Operations:

JavaScript variables can hold numbers, yes. They have all the basic operations that you would expect. Variables containing numbers can be added, subtracted, multiplied, and divided. There are, however, many shortcuts to these operations. For instance, say you have this:

var num = 10;
num = num + 12;

This can be condensed to this:

var num = 10;
num += 12;

The += operator replaces num +. There are also the -=, *=, /=, and %= operators which work the same way. The % operation, if you have not seen it before, is the remainder operator. That is 12 % 5 is equal to 2. There are two more shortcut operators for numbers, the ++ and --.

num++; equals num = num + 1; equals num += 1;

The -- operator works in the same way, but subtracts one.

 

 

JavaScript: More on Variables - Strings


Strings:

Strings are to be enclosed by quotation marks. A string can be enclosed by either double (") or single (') quotation marks. The marks must be paired however. That is to say, if you use a double quotation mark to start a string, then you must end the string with a double quotation mark. Here are some valid strings:

"Hello World"
'Hello World'


Special Characters:

As you can see, you cannot hold a double quotation mark in a string if you are bounding the string with double quotation marks. In order to store the double quotation mark, as with other characters, you must use special characters.

Character

Meaning

\b

Backspace

\f

Form feed

\n

New line

\r

Carriage return

\t

Tab

\'

Single quote or apostrophe (')

\"

Double quote (")

\\

Backslash (\)

\XXX

XXX is an octal number (between 0 and 377) that represent the Latin-1 character equivalent. For example \251 is the octal code for the copyright symbol.

\xXX

XX is a hexadecimal number (between 00 and FF) that represent the Latin-1 character equivalent. For example \xA9 is the hexadecimal code for the copyright symbol.

\uXXXX

XXXX is a hexadecimal number (between 00 and FF) that represent the Unicode character equivalent. For example \u00A9 is the hexadecimal code for the copyright symbol. (Note: Unicode is only supported by JavaScript 1.3)

The string "\tTom said \"Hello to everyone!\"\nSo did Mary." would print:

      Tom said "Hello to everyone!"
So did Mary.


String Operations:

String variables also have their own operations. Strings can be added together with the + operator. This can be used in two ways:

var str = "string one" + " string two";

- or -

var str1 = "string one", str2 = " string two", str;
str = str1 + str2;

In both cases the str variable would equal "string one string two". The += operator also works with strings. It works same the way for strings as it does with numbers. Besides these operators, strings have other abilities. We will not cover all of the different string abilities, instead we will look at only a few. One is the length property. Here is how it works:

var text = "Hello World!";
var num = text.length;

num will equal 12, the number of characters in the text string.

Another ability of strings is the indexOf(searchString). This command will find the index of the first occurrence of the searchString. Take this for example:

var str = "Hello World!";
var num = str.indexOf("World");

The variable num will end up with the index of 6, the position of where "World" starts in the str string. The string indexing starts with zero and ends with one less than the string's length. That is, the length of str is 12 and the index of "!", the last character in the string, would be 11. Again, if you have a string and the given searchString occurs more than once within it, the index of the first occurrence of it will be returned. For instance:

var str = "she sells sea shells by the sea shore";
var num = str.indexOf("sea");

The number returned to num is 10; this is where the first "sea" occurs. It is important to note that the indexOf command is case sensitive. That is, if we used the search string of "SEA", then indexOf would not have found an index in the above str string. When indexOf fails to find a search string then the index of -1 will be returned.

Also, with JavaScript 1.2 (for newer browsers like Netscape Navigator or Microsoft Internet Explorer, versions 4.0 and higher) a substring can be taken from a variable using the substr(startingIndex, endingIndex) command. If this were to be done:

var text = "Hello World!";
var text2 = text.substr(6, text.length);

then text2 would equal "World!". The substr command requires two values: a starting index and an ending index. Of course, the starting index is which character of the string to start the substring with and the ending index is which character of the string to stop the substring with. The starting index starts with zero and works it way up to string.length - 1. The ending index is one greater than the starting index and so starts with one and ends with string.length. This indexing scheme would then make the first character of a string be found at string.substr(0, 1) and the last character be found at string.substr(string.length - 1, string.length).

Also, all three commands we just looked at for strings, length, indexOf, and substr work on literal strings as well. This means that following commands are valid:

var num = "Hello World!".length; /*num would equal 12*/
var num2 = "Hello World!".indexOf("W"); /*num2 would equal 6*/
var text = "Hello World!".substr(num2, num); /*text would equal "World!"*/

 

 

JavaScript: More on Variables - Variable Type Conversions


Variable Conversion:

If you want to convert between numbers and strings, then you can use the two built-in functions: Number(objectName) and String(objectName). Here is how you cold use these functions:

var num1 = 123, num2, num3, str1 = "321", str2, str3;
num2 = Number(str1);
num3 = num1 + num2;
str2 = String(num1);
str3 = str1 + str2;

num3 would end up with the value of 444 and str3 would end up with the value of "321123". If the string were to contain something other than numeric digits, however, then the Number function would return a value of NaN (Not a Number). The Number function also assumes that it is given a decimal number. That is, if an octal number was given to it in string from, say "012", then the decimal number of 12 would be returned. Also, as just hinted, a hexadecimal number of "0x12FF01" would fail and return NaN.

If you expected to get an octal or a hexadecimal number in string form, and wanted to used it as a number, than you would have to do some manipulation JavaScript does, however, do some conversions on its own. If you were to add a number to a string, then JavaScript would convert the number to a string and add it to the string. On the other hand, if you try an operation other than addition then JavaScript will attempt to convert the string into a numeric value and carry out the requested expression. If the string does not contain all numeric values, then a value of NaN would be returned after the expression was attempted.

var str1 = "123", str2 = "123a", num1 = 12;
var strAnswer = num1 + str1; /*will equal "12123"*/
var numAnswer1 = str1 - num1; /*will equal 111*/
var numAnswer2 = str2 * num1; /*will equal NaN*/

 

 

 

 

JavaScript: Function Parameters and Returns

Here, we will take a closer look into JavaScript functions. We will cover:

 


Function Parameters:

First, go ahead and type a message into the text field and then push the button.

<html>
<head><title>The Title</title>
<script language="javascript">
<!-- begin code hiding
     //this function will run the JavaScript alert box
     //and display the given text when called.
           function MsgBox(text)
           {
               alert(text);
           }
// end of hiding -->
</script>
</head>

<body>
<form>
     <input type=text name="text1" size=20>
     <input type=button name=b1 value="push me" onClick="MsgBox(form.text1.value)">
</form>
</body>
</html>

You will see that MsgBox now takes a variables. That variable is called a parameter. Function parameters are variables (which are not declared with var) that a function will need to carry out its task. In this case MsgBox needs a string to pass to alert (remember that alert is a function and that string that it needs is a parameter). MsgBox is passed a string when the onClick event handler calls it. What is this form.text1.value you ask? It is the string value of the text field that was named text1, which is part of this form. form and text1 are known as objects and value is called a property of the text1 object. We will take a better look at objects and their properties latter on.

A function can take more than one parameter. Remember the substr command for strings? You can think of that as a function, for now. It required two parameters, a starting index and an ending index. These values were separated by a comma. If you cannot remember the substr command, here it is again:

string.substr(startingIndex, endingIndex)

Remember that when you make a function that takes parameters to send it what it wants. Also, for those of you who are used to programming in languages like C++ and Java, you cannot overload function names by changing the number of parameters. This means that a browser will not distinguish between these two functions:

function foobar(param1, param2) {. . .}
function foobar() {. . .}

The browser will pick one of these functions and go with that one only.

 


Function Returns:

Not only can a function take parameters; they can return values. Functions can also return one and only one value, however. To do this all you need is the return followed by a return value. Here is an example of the code.

function foo()
{
     return someValue;
}

Here is an example of how this return statement can be used:

<html>
<head><title>The Title</title>
<script language="javascript">
<!-- begin code hiding
     function doAddition(num1, num2)
     {
           var answer = doWork(num1, num2);
           alert(String(num1) + " + " + String(num2) + " = " + String(answer));
     }

     function doWork(num1, num2)
     {
           return num1 + num2;
     }
// end of hiding -->
</script>
</head>

<body>
<form>
     <input type=button value="push me" onClick="doAddition(25, 45)">
</form>
</body>
</html>

Go ahead and copy the code and give it a try.

 

 

 

JavaScript: Conditional Statements - The Conditions

Can you think of a programming or scripting language that does not have some sort conditional statement? I can't and JavaScript is no exception. JavaScript has a couple of different type of conditional statements:

Before, we dive into conditional statements we must first understand conditions. When I write conditions, I am referring to statements any JavaScript statement that can evaluate to true or false. A condition can be as simple as a variable that contains either a boolean (TRUE or FALSE), numeric, or string value. As you can guess, the boolean value is made for conditions. Numeric and string values, on the other hand are not as obvious. With numbers, you can use the traditional zero (0) to evaluate to false. Any other number will be true. With strings the empty string ("" or '') will evaluate to false.

Variables or objects that contain a value of
undefined or expressions that evaluate to NaN (Not a Number) also give a value of false.

Functions can also be used as condition statements. Remember when we went over function returns? As you recall, function returns return a value, which can be tested like any variable. Here are some examples of the above conditions that could be used within the
if statements:

if( true ) . . .; /*evaluates to true*/


var foobar = "";
if( foobar ) . . .; /*evaluates to false (empty string)*/


var num = 0; /*numeric zero*/
if( num ) . . .; /*evaluates to false (zero)*/


var str = "0"; /*string containing the number zero*/
if( str ) . . .; /*evaluates to true (non-empty string)*/


var noVal; /*not set to any value (undefined)*/
if( noVal ) . . .; /*evaluates to false (undefined variable)*/


if( document.foobar[0] ) . . .; /*evaluates to false (undefined object)*/


function isOK() {
      return true;
}

if( isOK() ) . . .; /*evaluates to true (the isOK() function returns true)*/


if( "foobar" * 12 ) . . .; /*evaluates to false (NaN, the string "foobar" cannot be multiplied to a number)*/

Condition statements can be more complicated than just a simple call to a variable. This can be done by using comparison and logic operators. You can use the equality operator to test if two variables are equal to each other, or you can use the logical AND operator if more than once condition must be met. Here is a table of JavaScript's condition and logic operators:

Comparison Operators

Operator

Description

1.3

Example

==

Equal to. This will try to convert operands to similar types and compare if they are of different types.
Note: This has two equal symbols. If only one equal sign is used, then a assignment will be executed instead of a comparison.

 

push for example

!=

Not equal to. This will try to convert operands to similar types and compare if they are of different types.

 

push for example

===

Strict equal to. This will return true only if the operands' types are the same and their values are equal to each other.

x

push for example

!==

Strict not equal to. This will return true if the operands' types are not the same or their values are not equal to each other.

x

push for example

>

Greater than. JavaScript will try and convert to similar types for the comparison.

 

push for example

>=

Greater than or equal to. JavaScript will try and convert to similar types for the comparison.

 

push for example

<

Less than. JavaScript will try and convert to similar types for the comparison.

 

push for example

<=

Less than or equal to. JavaScript will try and convert to similar types for the comparison.

 

push for example

Logic Operators

&&

Logical AND. Returns true if both operands are true.

 

push for example

||

Logical OR. Returns true if either or both operands are true.

 

push for example

!

Logical NOT. Returns the opposite Boolean value for the operand.

 

push for example

Note: The comparison operators that are marked with an "x" are from JavaScript 1.3 and may not be implemented with your browser.

Now that you have seen all the different operators we will look at how to use some of them. To do a quick equality comparison between to values, then you would use the the double equal operator, like this:

if( "hello" == "hello" ) . . .; //evaluates to true

Remember that you must use the double equal sign (==), do not use the single equal (=). This is a common mistake and is one that is not quite as obvious as others that you can make. The single equal sign is an assignment operator. That means that if you had

if( someVar = "TUCOWS" ) . . .;

then no matter what value someVar contained, the condition would be true. That is because the assignment operator returns the value that is being assigned. In this case the string "TUCOWS" would be return, which is not an empty string and so is not false. Not only would you always have the condition return true, you would also have someVar assigned to the string "TUCOWS".

The equality comparison operator, as with the other comparison operators, is case sensitive. In other words this means that the strings "Hello" and "hello" are not the same. JavaScript will try to convert between numeric and string value types when a comparison is made between the two types. For example, this bit of code would return true:

if( "12" == 12 ) . . .;

With, JavaScript 1.3 (Netscape 4.5 and above) the strict equal and not equal comparison operators are available, however. These will compare values and types. If you used the strict equal operator in the example above, then the condition would have returned false since the types of the values were different. To get further explanations on the different operators, then please refer to the above table.

Now, this brings us to the logical operators. Here we have access to the logical AND (
&&), OR (||), and NOT (!). These would work as you would basically expect. With the AND and the OR, you can use more than one condition to test for. This could be the form for the logical AND and OR:

if( condition1 && condition2 ) . . .; /*this will only return true if both conditions are true*/


if( condition1 || condition2 ) . . .; /*the condition will only return false if both conditions are false*/

You will often see that conditions are grouped with parentheses. Grouping conditional help keep things in easy to handle sections.

As you can guess, the NOT operator will return false if the condition it is attached evaluates to true, otherwise it returns true. That is:

if( !true ) . . .; /*the condition will evaluate to false*/


if( !"" ) . . .; /*the condition will evaluate to true*/

One more thing about the logical operators. The logical AND and OR are both none as short circuiting. That is, they will evaluate a condition as far as it is needed and so may not actually test all the conditions. Here is what this means:

false && some other condition //returns false
true || some other condition //returns true

In both examples, the "some other condition" will not be tested. This is because an AND statements must have both conditions to be true, if the first one is false, then the second condition does not matter. The same goes for the OR, which must have both conditions to be false for the whole statement to be false

JavaScript: Conditional Statements - The if Statement

Here we have the if/else statement. The if statement in its simplest form looks like this:

if( condition )
      code to execute if condition is true;

As you can see, after the condition comes the bit of code that is executed if the condition is true. In the above example, I assumed that only one command was to be used. If, however, you needed to do more then one line will allow, then you must "block" your code in with curly brackets ({ and }), kind of like functions. This is how a blocked if statements might look like:

if( condition )
{ //if the condition is true
      some code;
      some code;
      some code;
. . .
}

As you can see, each line of code within the block still must end with a semi-colon.

If the simple form of the if statements is too simple, then you could add the else. Here is how that would look:

if( condition ) {
      some code if the condition is true;
      some more code;
      some more code;
} else {
      some code if the condition is false;
      some more code;
      some more code;
}

The code that is contained within the else statement is executed only if the condition is false.

With the help of else the if statement can become very complicated. if statements can be placed within other if statements creating many branches that a script can follow. Also, in a more linear fashion, if/else statements can be placed within long lines. Here are some examples of both:

if( condition ) {
      if( condition ) {
            some code;
      } else {
            if ( condition ) {
                  some code;
            } else {
                  some code;
            }
      }
}

// --or--

if( condition ) {
      some code;
      some code;
} else if( condition ) {
      some code;
} else if( condition ) {
      some code;
      some code;
} else {
      some code; }

The first example can get very confusing, so it may be best to try to keep embedding if statements down to a minimum, but there are times when it is almost unavoidable.

Now that we have discussed the if/else statement, lets see what we can do with switches.

JavaScript: Conditional Statements - Switches

With version 1.2 came the switch to the JavaScript language. What is the switch? Well, it is pretty much like a series of if/else statements that tests a variable with a series of values. Here is an example of a switch:

switch( someVar ) {
      case someValue1:
            some stuff;
            break;
      case someValue2:
            some stuff;
            break;
      case someValue3:
            some stuff;
            break;
      . . .
      default:
            some stuff;
}

Here is how this switch may look as a bunch of if/else statements:

if( someVar == someValue1 ) {
      some stuff;
} else if( someVar == someValue2 ) {
      some stuff;
} else if( someVar == someValue3 ) {
      some stuff;
} . . .
else {
      some stuff;
}

The switch can be a little easier to read and less to type. Here is the low-down on how this thing works. First, the switch must be passed a variable to test, which is the someVar as seen above. Next, each case will have the value that the variable will be compared to. This value can be either a number or a string. The value is then followed by a colon (:), which in turn is followed by the code to execute. If the variable and the case value match, that is if they are equal to each other, then the code under it will be executed. The last part of each case is the break. This "breaks" out of the switch so that the rest of the cases are not tested. At the end of the switch you will see default. This does basically what the last else did in the series of the if/else statements. The default is executed if none of the cases matched the given variable.

Switches are not really all that difficult to use. Again, they make things easier to read and follow. Remember, however, that the
switch command is not part of the JavaScript language until version 1.2.

 

 

JavaScript: Condition Statements - The Condition Operator

For those who just cannot get enough condition statements, or for those looking for more short cuts, then the condition operator is what you are looking for. Here is an example of this operator:

condition ? val1 : val2

What this conditional operator does is test the condition, if it returns true, the first value (val1) will be returned. Otherwise, the second value (val2) will be returned. This is something that you are likely to see in the code if someone decides to use this operator:

var alertText = (yourGuess == answer) "You got it right" : "Sorry";

You could also execute a command instead of just using a string. However, you are limited to only one command if the statement is true and one if it is false. If you need to run a block of commands, then you will have to deal with an if/else statement.

That is about it for conditional statements. Let us now move on to loops.

 

 

 

JavaScript: Loops

Loops are what they sound like. They run a sequence of code as long as a certain condition is met. There are three kinds of loops in JavaScript.

 


while Loops:

Here is the basic structure for the while loop:

while(condition)
{
      . . .stuff to be executed
}

The condition, like with the if statement, can be any JavaScript truth giving expression. The while has the possibility of not running at all, since the condition is checked before the loop is entered (or reentered).

 


do...while Loops:

The do...while loop is much like the while loop, but the condition is checked after the loop runs once. This loop will then always run at least one time. Here is how the do...while loop works:

do
{
      . . .stuff to be executed
}
while(condition)

 


for Loops

The for loop works differently from the while and the do...while loops. Here is how it looks:

for(initialExpression; condition; incrementExpression)
{
      . . .stuff to be executed
}

The initialExpression is some variable that will be used in the condition. It is initialized to some value, which the loop will start with. The condition uses the variable set in the initialExpression section and can be any JavaScript truth giving expression. The incrementExpression is where the variable is incremented. This may seem a bit confusing, so here is an example:

var str = "";
for(var counter = 0; counter < 3; counter++)
{
      str += "Hello ";
}

After this loop finishes, the string str will be "Hello Hello Hello ". The variable counter is initialized to be equal to zero. Then, as long as counter is less than 3, then the string "Hello " is added the str. Here is a quick table showing the values of the different variables after each run of this loop:

Run #

str

counter

0

""

0

1

"Hello "

1

2

"Hello Hello "

2

3

"Hello Hello Hello "

3

After run three finishes and before run four starts the condition is tested (which is counter < 3) which is found to be false because 3 is not less than 3.

Here are possible ways of doing the above example with both the while and the do...while loops:

while:


var str = "", counter = 0;
while(counter < 3)
{
      str += "Hello ";
      counter++;
}

do...while:


var str = "", counter = 0;
do {
      str += "Hello ";
      counter++;
} while(counter < 3)

Remember, even though the code is basically the same for both the while and the do...while loops, they do not function exactly the same. If the counter variable was initialized to 3 before the loops, the while loop would not have run, but the do...while loop would have run once.

 

 

 

JavaScript: Controlling Loops

1