Loops, Versions, navigator Object
(Lesson 10)

for Loop

A repeat loop cycles though a group of statements until some condition is met. For instance, you can use a repeat loop to cycle though an array and print it to the screen. Or, you might want to cycle though the Array and look for some specific information using the if statement. The for loop is the most common used repeat loop. Here is the syntax for it.

``` for ( [initial exp.]; [condition]; [update exp.] ){
statements
}
```

The square bracket means that the parameter is optional. I always use all three parameters and think you will too.

The initial expression defines the starting point of the of the loop. It sets the value of a variable to some value. The condition tests the variable for a certain condition and when it is reached stops the loop and lets the code after the for loop execute. The update expression determines how the variable is incremented.

Here is a simple example. We will use the "for loop" to print the numbers 1 through 5 to our screen.

Here is code

``` var i
for(i=1; i<=5; i++){
document.write(i + "<BR>")
}
```

and here are the results.

You can declare the variable as part of initial expression. In fact this is usually the way it is done. Here is our simple script with this change.

``` for(var i=1; i<=5; i++){
document.write(i + "<BR>")
}
```

Sometimes you may want to break out of a loop or skip part of a loop. The break statement allows you to get out of a loop if some specific condition occurs. This is done by detecting the condition with an if statement that executes the break statement. You will see an example of this in the upcoming script for generating a JavaScript calendar. The continue statement will allow you to skip any statements below it and start the loop over.

Lab Time

Try these two problems in our lab.

1. Write a simple script to print the numbers 1 through 10 on the screen.

2. Write a script to print the numbers starting with 10 and ending with 1 (hint, you will use something like i-- instead of i++. You will also have to change your initial expression and condition).

Once you have done all of these you can take a look at my solutions to see if I did it right.

A JavaScript Calendar

One of the neat things you can do using a "for loop" is to generate a calendar like the one shown below.

The script for this calendar is contained in one function that has a month and year as it's parameters. This function can be used to print a calendar for any month and year after the magic date of January 1, 1970 when JavaScript time started. Here is the source code for the function.

This is the most complex script that we have done. If you exam it carefully and look at it in sections by the comments I have, I think you will realize that it really is not all that complicated. I first create three Array objects to contain data we will need later. I then create a date object for the first day of the month using the parameters, month and year, that were passed to our function. Then I get the number that represents the day of the week that the first of month falls on. Here I get a little tricky. I make this a negative number. I do this so that later when we put it in a loop that will be incremented by one, I can check this number with an if statement and print a space if it is below 0 or the number if it is greater than 0. That's how I get the blank cells in the table before the 1st of the month.

The rest of the script is used to construct a string that will be returned to be printed to the document. I use a series of loops to construct a couple of tables. The first one is formatting to line up the Month and Year display at the top of calendar with the calendar itself. The second table is the calendar. Notice I did use a break statement close to the end of the script. This was because I did not know how many rows would be needed and I used it to stop making the rows.

Here is the script I put in the body of the document. I used a date object to first determine what this month and year is and passed these values to the function. You can call the function without doing this if you have a particular month and year you want to print a calendar for.

```
<SCRIPT language="JavaScript"><!--
var today = new Date()
var curMonth = today.getMonth()+1
var curYear = today.getYear()
if(curYear < 1000){
curYear += 1900
}
document.write (getCalendarForMonth(curMonth, curYear))
//--></SCRIPT>
```

Note that the if statement

``` if(curYear < 1000){
curYear += 1900
}
```
is used to correct for Y2K.

Here is how you would call the function to print a specific month, for example February of 2000 (note that a 4 digit year is used).

``` document.write (getCalendarForMonth("2", "2000"))
```

Here is the result.

while and do-while Loops

Two additional repeat loops are available in JavaScript. The while loop tests the supplied condition and continues to execute until it is met. Here is the syntax for it.

``` while (condition){
statements
}
```

Here is the syntax for the do-while loop.

``` do{
statements
} while (condition)
```

The primary difference between these two loops is that the "do-while loop" will always execute one time whether the condition is true or not whereas the "while loop" will only execute if the condition is true.

I could have used one of these loops to replace the "for loops" in our calendar. This would have eliminated the need for the break statement. However, I am not convinced that either of these loops have a lot to offer over the "for loop". Again, it is your choice.

Be aware that when you are using any of the loops that you can set up a condition that will cause a continuous loop if you are not careful with your coding. This will cause your page to hang up. So make sure that the condition that will stop execution of the loop is a realistic condition that will be met.

Versions of JavaScript

Most text books talk about the versions of JavaScript in the early chapters. I have waited until close to the end of this class to discuss this topic because I felt it was important that you understand how to use JavaScript first.

There will be times that you want to design a script that includes the functionality that is not available in some older JavaScript enabled browsers, such as Internet Explorer 3 or Netscape 3. You need to know how to accommodate the older browsers with your script. Knowing what versions of JavaScript are supported by what browsers and how to detect the versions in your scripts allows this.

There are currently four versions of JavaScript. Netscape 2 supported the original version 1.0. Netscape 3 and Internet Explorer 3 supported version 1.1. Netscape 4 and Internet Explorer both support version 1.2. Netscape 4.5 supports version 1.3. I am not sure what version will be supported by Internet Explorer 5.

Even though Netscape 3 and Internet Explorer claimed to both support version 1.1 of JavaScript, there was a considerable difference between the two. The difference between the versions in Netscape 4 and Internet Explorer 4 is much less making it much easier on us when we design our pages. I am talking about what I call conventional JavaScript. Cascading Style sheets and Dynamic HTML are still different in the two browsers.

Internet Explorer refers to it's version of JavaScript as JScript. JScript comes in versions 1.0, 2.0, and 3.0. JScript recognizes the "JavaScript" as a language property of the SCRIPT tag and is compatible with JavaScript as defined in the paragraph above.

The language property of the SCRIPT tag can be used to isolate scripts for specific versions of JavaScript by including the version. Here is the method you should use to allow for multiple versions of JavaScript.

``` <SCRIPT Language="JavaScript">
statements for all Versions
</SCRIPT>
<SCRIPT Language="JavaScript1.1">
statements for Versions 1.1 and later
</SCRIPT>
<SCRIPT Language="JavaScript1.2">
statements for Versions 1.2 and later
</SCRIPT>
<SCRIPT Language="JavaScript1.3">
statements for Version 1.3
</SCRIPT>
```

Notice that the above snippet of code contains 4 <SCRIPT> tags. Also note that the language property is different for each. This is how you isolate scripts for specific versions of JavaScript. Most of the time you will only use the first one, which is what we have been doing. However, if you want to use some code that only works for a specific version, then you must include the <SCRIPT> tags for that one too.

For example, suppose you write a great function that only works in JavaScript version 1.2. Then, you must place it between the <SCRIPT> tags for version 1.2. You must also include the top tag to accommodate older browsers with a different version of your function in it. Here is what it would look like.

``` <SCRIPT Language="JavaScript">
function myGreatFunction(){
my statements for versions prior to Version 1.2
}
</SCRIPT>
<SCRIPT Language="JavaScript1.2">
function myGreatFunction(){
my statements for Version 1.2
}
</SCRIPT>
```

The bottom myGreatFunction() would be executed on browsers that support JavaScript version 1.2 or later whereas the top myGreatFunction() would be executed on browsers that supported JavaScript version 1.0 or 1.1. Notice that the newer version scripts are placed last. Also notice that you only have to include <SCRIPT> tags for the versions that are directly affected. There will be times that the function that you place in the upper <SCRIPT> tag will just be a dummy function that does nothing but it must be there to prevent JavaScript errors.

<NOSCRIPT> tag

Use the <NOSCRIPT> </NOSCRIPT> tag to inform users that their JavaScript is currently turned off. You might want to provide some guidance for turning it back on too.

navigator Object

There will be times when you need to be able to detect information about the browser a surfer is using. Most of the time this will be so that you can initiate different portions of your scripts because of the inconsistency of versions between the browsers. You will use the navigator object to accomplish this.

The navigator object has 8 properties which are listed below with the value for the particular Browser you are now using.

navigator.appName

navigator.appCodeName

navigator.appVersion

navigator.language

navigator.mimeTypes[]

navigator.platform

navigator.plugins[]

navigator.userAgent

The appName property contains the official name of the browser application. This is Netscape for Netscape browsers and Microsoft Internet Explorer for Internet Explorer Browsers. Both browsers display Monzilla for the appCodeName property. The appVersion and userAgent contain information on the browser's version, platform of the Browser, and the country for which the browser is released. The language property contains a two letter code to indicate the localized language version of the program. The platform property reflects the operating system but is only available beginning with the version 4 browsers. The mimeTypesand plugings are both array objects. The mimeTypes contains a listing of files of the type MIME (Multipurpose Internet Mail Extension) that is quite extensive. I just showed the length property for it here. I really don't know of what use this information could be. The plugins object contains information on the plugins that are available in Netscape. I listed its name property above. It also has three other properties and one method.

If you view this using Internet Explorer, you will notice that the language property above is undefined. Also, the number of mimeTypes will be shown as 0 and the plugins will be blank. This means that these three properties will not be very useful to you. However, the appName, appVersion and userAgent properties are available in all browsers, since Netscape 2 and Internet Explorer 3. These three properties should be useful for determining information on browsers and platforms.

The navigator object has three methods, JavaEnabled(), preference(), and taintEnabled(), which will not be covered here because I feel there intended use is more advanced.

Assignment

1. Create an array containing the name of days of the week and then use the "for loop" to print out the array. Use the length property to determine the size of the array.
Solution   Source

2. Write a script to print the numbers 1 through 20. Your results should be printed on 4 lines with 5 numbers on each line. Be sure to put a space between the numbers that are on the line. This will require a loop inside of a loop. I recommend that you get one loop working and the add the second.
Solution #1   Source #1      Solution #2   Source #2
I think that you will find that the second method displays faster.

3. Write a script that will determine the version of JavaScript. Make sure that it also determines if JavaScript is enabled.
Solution   Source

4. Write a script that will determine what type of browser is being used.
Solution   Source

[ Top of Page  |  Contents ]