Availability: |
| ||||||||
JavaScript syntax: | - | aLabel: if(aCondition) { someCode} | |||||||
Argument list: | aCondition | An expression that yields a Boolean value | |||||||
aLabel | An optional identifier to name the if block | ||||||||
someCode | Some script source text that is executed if the condition tests true |
The if() statement is used to conditionally execute a code block depending on the result of a conditional expression. This mechanism is called branching.
The expression in the parentheses is evaluated and cast to a Boolean value. If it yields a true value as a result, then the code in the associated block is executed. Otherwise, the code is ignored and execution continues at the line following the closing brace of the code block.
JavaScript allows you to omit the braces around the code block if the code is a single line. You must place the trailing semi-colon on the line to delimit the script source text that is associated with the if() statement.
At version 1.2 of JavaScript, you can name the if statement and use the labeled form of the break keyword to exit the conditional code block prematurely.
Beware of leaving the braces off the associated script source text as it is possible for this to be ambiguous to the reader and can lead to difficulties when adding more code to be executed conditionally. It can become easy to add a second line of code but still omit the braces. In that case, only the first line will be conditional but the second will always be executed regardless of the result of the if() condition. This can lead to completely unexpected behavior and is quite difficult to diagnose.
// Recommended form if(a == b) { z = 100; } // Possibly dangerous during maintenance if(a == b) z = 100;
ECMA 262 edition 2 - section - 12.5
ECMA 262 edition 2 - section - 12.6.1
ECMA 262 edition 3 - section - 12.5
Wrox Instant JavaScript - page - 22
Prev | Home | Next |
IEEE 754 | Up | if( ... ) ... else ... |
JavaScript Programmer's Reference, Cliff Wootton Wrox Press (www.wrox.com) Join the Wrox JavaScript forum at p2p.wrox.com Please report problems to support@wrox.com © 2001 Wrox Press. All Rights Reserved. Terms and conditions. |