Software Sue

Link to Simply Sue
Link to Sustainability Sue
location: software/scripting/javascript/if and else operators Skip navigation : Home  

JavaScript If & Else Operators


if

The basic if statement takes the form:

if ( expression )
     { statement }

The expression should be in parentheses. A single statement does not need curly brackets but multiple statements should be grouped within curly brackets.

For example:

var a=2;
var b=5;
if (a == b)
{
document.writeln("Behold! a and b are the same!");
}

The code fragment above would cause no alert, whereas the code fragment below would

var c=5;
var d=5;
if (c == d)
{
document.writeln("Behold! c and d are the same!");
}

For more details of the expressions that can be used to compare two operands, see comparison operators.

You can test more than one thing at a time. The first code fragment below tests if both a and be are the same, and c and d. It will not generate a message in this example. The second code fragment tests if a = b OR c = d, and it will produce an alert in this case.

if ((a == b) && (c == d))
{
document.writeln("Wow! a = b and c = d!");
}

if ((a == b) || (c == d))
{
document.writeln("One out of 2 isn't bad! a = b or c = d!");
}

(The javascript for the 4 tests above follow in the code, but with each document.writeln commented out. Just view source and un-comment them to try the code out).

if/else

To carry out one action if the condition is true, and another if it is false, use an else. For example:

if (a == b)
{
document.writeln("Behold! a and b are the same!");
}
else
{
document.writeln("Beware! a and b are different!");
}

You can combine an else clause with a nested if/else statement to produce an else/if statement. For example:

if (a == b)
{
document.writeln("Behold! a and b are the same!");
}
else if (a < b )
{
document.writeln("a is less than b!");
}
else
{
document.writeln("a is greater than b!");
}