Internet Systems
80
Chapter 8. JavaScript: Control Structures I
JavaScript supports the usual control structures.
JavaScript supports abbreviated assignment operators of the form:
op=
Example:
x += y;
JavaScript supports the increment and decrement (both pre- and
post-) operators of C++.
Example:
x ++ ;
When a variable is declared but not given a value, it has an
undefined value.
To indicate that a variable doesn’t contain a value, you can
assign the value null to it.
Internet Systems
81
Chapter 9. JavaScript: Control Structures II
You can use control structures to get display effects.
Example:
<script type = "text/javascript">
for ( var counter = 1; counter <= 5; ++ counter )
document.writeln( "<p><font size = '" + counter +
"'>HTML font size " + counter + "</font></p>" );
</script>
HTML font size 1
HTML font size 2
HTML font size 3
HTML font size 4
HTML font size 5
For each value counter 1-5, this code sends document the string
<P><font size = “counter”>
HTML font size counter</font></p>
Internet Systems
82
JavaScript has the C++ logical operators (!, &&, ||) and constants true
and false.
Example:
<script type = "text/javascript">
var choice,
startTag,
endTag,
validInput = true,
listType;
choice = window.prompt( "Select a list style:\n" +
"1 (bullet), 2 (numbered), 3 (lettered)", "1" );
switch ( choice ) {
case "1":
startTag = "<ul>";
endTag = "</ul>";
listType = "<h2>Bullet List</h2>";
break;
case "2":
startTag = "<ol>";
endTag = "</ol>";
listType = "<h2>Ordered List: Numbered</h2>";
break;
case "3":
startTag = "<ol type = 'A'>";
endTag = "</ol>";
listType = "<h2>Ordered List: Lettered</h2>";
break;
default:
validInput = false;
}
if ( validInput ) {
document.writeln( listType + startTag );
for ( var i = 1;