11.12.2012 Views

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

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.

<strong>JavaScript</strong> supports a core set of statements that should be familiar to anyone who has<br />

programmed in a modern imperative programming language. <strong>The</strong>se include flow control (ifelse,<br />

switch), loops (while, do-while, for), and loop control (break and continue). <strong>JavaScript</strong><br />

also supports some object-related statements (with, for-in). Readers already familiar with such<br />

statements may want to skim this section, focusing only on the more esoteric aspects<br />

(particularly the short-circuit evaluation of if statements, the differences in switch support<br />

among versions of <strong>JavaScript</strong>, endless loop problems and Web browsers, and the use of break<br />

and continue with labels).<br />

if Statements<br />

<strong>The</strong> if statement is <strong>JavaScript</strong>‘s basic decision-making control statement. <strong>The</strong> basic syntax of<br />

the if statement is<br />

if (expression)<br />

statement;<br />

<strong>The</strong> given expression is evaluated to a Boolean, and, if the condition is true, the statement is<br />

executed. Otherwise, it moves on to the next statement. For example, given this script<br />

fragment,<br />

var x = 5;<br />

if (x >> 1)<br />

alert("x is greater than 1");<br />

alert("moving on ...");<br />

the expression evaluates to true, displays the message ―x is greater than 1,‖ and then displays<br />

the second alert dialog afterward. However, if the value of variable x were something like zero,<br />

the expression would evaluate false, resulting in skipping the first alert and immediately<br />

displaying the second one.<br />

To execute multiple statements with an if statement, a block could be used, as shown here:<br />

var x = 5;<br />

if (x >> 1)<br />

{<br />

}<br />

alert("x is greater than 1.");<br />

alert("Yes x really is greater than 1.");<br />

alert("moving on ...");

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

Saved successfully!

Ooh no, something went wrong!