Top » TUTORIALS » ELSE If you find this page useful
please make a secure donation
My Account  |  Cart Contents  |  Checkout   

Javascript Reserved Word - ELSE

ELSE is part of the IF.
ELSE can be used to have some javascript code run as a condition other than the main stream logic (expression) in the IF statement.

The basic syntax for an ELSE statement:



if (expression)
[{ [code;]+ }] | [code;]
else [{ [code;]+ }] | [code;]


You should already be fimilar with the IF logic. This ELSE allows you to have code run when the expression in the IF equates to a boolean false value.

Expressions that evaluate to a boolean false value are:
undefined, null, 0, false
All other things equate to a boolean true statement.

Very simple ELSE usage where these all output "It was False":


if (!1)
document.write("It was True");
else
document.write("It was False"); Note that "!" is "not" - so "not one" equates to boolean false.
if (0)
document.write("It was True");
else
document.write("It was False");
if (1 != 1)
document.write("It was True");
else
document.write("It was False");
Note that "!=" is the "is it not equal to" condition.

It follows that any complexity of the expression in the IF statement still results in a boolean value. When it is false, the ELSE portion will run.

The last part to mention about ELSE's is the ELSE IF:

if (!1) document.write("!1");
else if (!2) document.write("!2");
else if (!0) document.write("!0");
else document.write("There were all false."):

This will output "!0" as this is the first boolean expression that evaluated to TRUE.

ELSEs associate with the nearest if that it can see in its scope.