Export (0) Print
Expand All

if...else Statement (JavaScript)

Conditionally executes a group of statements, depending on the value of an expression.

if (condition)
   statement1
[else
   statement2] 

condition

Required. A Boolean expression. If condition is null or undefined, condition is treated as false.

statement1

Optional. The statement to be executed if condition is true. Can be a compound statement.

statement2

Optional. The statement to be executed if condition is false. Can be a compound statement.

It is generally good practice to enclose statement1 and statement2 in braces ({}) for clarity and to avoid inadvertent errors.

In the following example, you may intend that the else be used with the first if statement, but it is used with the second one.

var z = 3;
if (x == 5)
    if (y == 6)
        z = 17;
else
    z = 20;

The above example is equivalent to the following code:

var z = 3;
if (x == 5) {
    if (y == 6)
        z = 17;
    else
        z = 20;
}

Changing the code in the following manner eliminates any ambiguities:

var z = 3;
if (x == 5) {
    if (y == 6)
        z = 17;
}
else
    z = 20;

Similarly, if you want to add a statement to statement1, and you do not use braces, you can accidentally create an error:

if (x == 5)
    z = 7;
    q = 42;
else
    z = 19;

In this case, there is a syntax error, because there is more than one statement between the if and else statements. Braces are required around the statements between if and else.

Supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, Internet Explorer 8 standards, Internet Explorer 9 standards. See Version Information.

Show:
© 2014 Microsoft