Statement
Conditionally executes a set of statements based on the value of an expression.
if (condition)
statement1
[else
statement2]
Parameters
Condition
Required option. A Boolean expression . If the condition is null or undefined, then condition is treated as false.
Statement1
Options available. The statement to execute when condition is true . Can be a compound statement .
Statement2
Options available. The statement to be executed when condition is false . Can be a compound statement.
Description
It is usually a good habit to enclose statement1 and statement2 in braces ({}), which is clearer and avoids inadvertent errors.
Example
In the following example, you might want to match the else to the first if statement, but it actually matches the second.
if (x == 5) if (y == 6) z = 17;else z = 20;
Rewriting the code in the following way eliminates any ambiguity:
if (x == 5) { if (y == 6) z = 17; }else z = 20;
Similarly, if you want to add a statement to statement1without using curly braces, you may have an error:
if (x == 5) z = 7; q = 42;else z = 19;
In this case, there is a syntax error because there are more than one statement between the if and else statements. The statement between if and else requires curly braces.
Requirements
Version 1
Please see
Conditional operator (?:)