if( ... ) ... else ... (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} else { someOtherCode )
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
someOtherCodeSome script source text that is executed if the condition tests false

The if() ... else statement is used to conditionally execute one or other code block depending on the result of a conditional expression.

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 first associated block is executed. Otherwise, the code in the first block is ignored and the code in the block following the else keyword is executed.

Each else keyword for which the associated if() is ambiguous will be associated with the nearest possible if() that would otherwise have no corresponding else.

At version 1.2 of JavaScript, you can name the if statement and use the labelled form of the break keyword to exit the conditional code block prematurely.

Example code:

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

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

Cross-references:

ECMA 262 edition 2 - section - 12.5

ECMA 262 edition 3 - section - 12.5

Wrox Instant JavaScript - page - 22