Client-Side Scripting with JavaScript


Part 4 - Language Features

Program Flow

The for keyword can loop through commands:

     for (initial value, max value, increment) {
          statement1;
          statement2;
          statement3;
          }
		  
For example:
<SCRIPT LANGUAGE="JavaScript"> for (linenum=1; linenum <=5; linenum++) { document.write("<LI>This is line ", linenum); } </SCRIPT>

This would display:


The while keyword repeats while a condition is true:

<SCRIPT LANGUAGE="JavaScript"> testnum = 0; while ( (testnum < 1) || (testnum > 10)) { testnum = window.prompt('Enter number between 1 and 10: ', ''); } window.alert("Value: " + testnum + "\n Thank you!"); </SCRIPT>

Select this link to test it.


Conditionals

The if...else structure can check values and respond:


if (condition) { commands if true; commands if true; } else { commands if false; } <SCRIPT LANGUAGE="JavaScript"> if (hour < 12) {document.write("Good morning."); } else {document.write("Good afternoon."); } </SCRIPT> <SCRIPT LANGUAGE="JavaScript"> if (hour < 12) {document.write("Good morning."); } else if (hour > 18) {document.write("Good evening."); } else {document.write("Good afternoon."); } </SCRIPT>

Logical and Comparison Operators

== Equal to
!= Not equal
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
|| Logical OR
&& Logical AND

Arrays

Arrays can be defined as an ordered collection of data. To establish an array:

solarSys = new Array("Sun", "Mercury", "Venus", "Earth", "Mars"); The first item in the array has the index number 0, so solarSys[0] would be "Sun." The number of items in the array can be found with solarSys.length.

This example shows the use of some of these commands, including for, if, and array:

<SCRIPT LANGUAGE="JavaScript"> document.write("Objects in the Solar System:<BR><UL>"); solarSys = new Array("Sun", "Mercury", "Venus", "Earth", "Mars"); for (ssobject=0; ssobject < solarSys.length; ssobject++) { if (ssobject == 0) {planet = ""} else {planet = "Planet " + ssobject + " - "} document.write("<LI>" + planet + solarSys[ssobject]); } document.write("</UL><P>"); </SCRIPT>

Here's how that would look:



Exercise 3

Modify the function ListGrades to display an additional column for each student showing their letter grade. The grading scale is:

Hints:

Here's an example of how to do it.

Next Next: Event Handlers and Objects