An if statement is a program control construct. It controls the program flow based on a logical expression that evaluates either to true or false.
The structure of an if statement is as follows:
if (expression)
{
statement;
}
The statement is executed only if the expression is true.
For example:
var name;
if (name == "John")
{
say "Hello!"
}
This condition would say "Hello" if the variable name is set to "John", but not if it is set to "Mary".
The if statement can evaluate any expression that has a logical result, that is, true or false. The operators used in expressions are
- Comparison Operators
- < --> less than
- <= --> less than or equal to
- > --> greater than
- >= --> greater than or equal to
- Identity Operators
- == --> is equal to
- != --> is NOT equal to
Examples:
- (5 > 4)
- true, 5 is greater than 4
- (5 <= 4)
- false, 5 is not less than or equal to 4
- ("John" == "Mary")
- false, "John" is not equal to "Mary"
- ("John" != "Mary")
- true, "John" is not equal to "Mary"
You can, of course, put also mathematical expressions into the if statement:
(1 + 1 = 2)
would evaluate to true; more useful perhaps would be an expression like this:
var x = 5;
var y = 10;
if (x - y <= 0)
{
document.write("Error: Result exceeds lower limit");
/* ... now do something else here ... */
}
An if statement can evaluate more than one expression. All conditions must evaluate to true for the statements following the if test to be executed.
Each expression is evaluated individually first; then the results are compared based on a logical operator that stipulates the condition that the expressions must satisfy together. The operators are:
- && = logical AND
- || = logical OR
if (expression1 && expression2)
{
do something;
}
If expression1 and expression2 are true, do something.
if (expression1 || expression2)
{
do something;
}
If either expression1 or expression2 is true, do something.