23.07.2013 Views

JavaScript/JScript: Control Structures I - Pearson Learning Solutions

JavaScript/JScript: Control Structures I - Pearson Learning Solutions

JavaScript/JScript: Control Structures I - Pearson Learning Solutions

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

2008934301<br />

Chapter 14 <strong>JavaScript</strong>/<strong>JScript</strong>: <strong>Control</strong> <strong>Structures</strong> I 407<br />

Most <strong>JavaScript</strong> programmers prefer to write the preceding if structure as<br />

if ( grade >= 90 )<br />

document.writeln( "A" );<br />

else if ( grade >= 80 )<br />

document.writeln( "B" );<br />

else if ( grade >= 70 )<br />

document.writeln( "C" );<br />

else if ( grade >= 60 )<br />

document.writeln( "D" );<br />

else<br />

document.writeln( "F" );<br />

The two forms are equivalent. The latter form is popular because it avoids the deep indentation<br />

of the code to the right. Such deep indentation often leaves little room on a line, forcing<br />

lines to be split and decreasing program readability.<br />

It is important to note that the <strong>JavaScript</strong> interpreter always associates an else with<br />

the previous if, unless told to do otherwise by the placement of braces ({}). This is<br />

referred to as the dangling-else problem. For example,<br />

if ( x > 5 )<br />

if ( y > 5 )<br />

document.writeln( "x and y are > 5" );<br />

else<br />

document.writeln( "x is 5" is<br />

output. Otherwise, it appears that if x is not greater than 5, the else part of the if/else<br />

structure outputs the string "x is 5" );<br />

else<br />

document.writeln( "x is 5"—is displayed.<br />

However, if the second condition is false, the string "x is 5" );<br />

}<br />

else<br />

document.writeln( "x is

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!