if( ... ) ... (Selector)

A conditional execution mechanism.

Availability:

ECMAScript edition - 2
JavaScript - 1.0
JScript - 1.0
Internet Explorer - 3.02
Netscape - 2.0
Netscape Enterprise Server version - 2.0
Opera - 3.0
JavaScript syntax:-aLabel: if(aCondition) { someCode}
Argument list:aConditionAn expression that yields a Boolean value
aLabelAn optional identifier to name the if block
someCodeSome 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.

Warnings:

Example code:

   // Recommended form
   if(a == b)
   {
   z = 100;
   }
   // Possibly dangerous during maintenance
   if(a == b)
   z = 100;

See also:Code block delimiter {}, Compound statement, Conditionally execute (?:), else ..., else if( ... ) ..., Flow control, if( ... ) ... else ..., Obfuscation, Selection statement, Statement, switch( ... ) ... case: ... default: ..., while( ... ) ...

Cross-references:

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