if....else
construct
JS Home <<
JS Reference <<
if....else
Allows the programmer to compare two operands and take subsequent action.
Description
Create a conditional statement using one of the comparison operators available in Javascript to test one operand against another. We can execute one set of statements if the boolean result of the expression evaluates
to true
and another if the expression evaluates to false
.
The comparison operators are discussed in detail in JavaScript Reference - Comparison Operators
- Using bracket notation
{ }
to wrap statements is optional, but good practice and will be used here.
Signature | Description |
---|---|
Simple if | |
if (condition) { | Execute statements in statement1 if condition expression evaluates to true . |
if....else | |
if (condition) { | Execute statements in
statement1 if condition expression evaluates to true , otherwise execute statements in statementN . |
Multiple if....else | |
if (condition) { | Execute statements in statement1 if expression condition evaluates to true Execute statements in statement2 if condition2 expression evaluates to true etc..., otherwise execute statements in statementN . |
Parameters
Parameter | Description |
---|---|
condition | An expression that evaluates to true or false . |
statement1 | Statements to execute when condition expression evaluates to true . |
condition2 | An expression that evaluates to true or false . |
statement2 | Statements to execute when condition2 expression evaluates to true . |
condition3 | An expression that evaluates to true or false . |
statement3 | Statements to execute when condition3 expression evaluates to true . |
statementN | Statements to execute when all other expressions have evaluated to false . |
Examples
The code below shows the multiple if....else construct.
// Compare some operands.
var aVariable = 4, bVariable = 2, cVariable = 3, dVariable = 4;
if (aVariable == bVariable) {
alert('statement 1 executed');
} else if (aVariable == cVariable) {
alert('statement 2 executed');
} else if (aVariable == dVariable) {
alert('statement 3 executed');
} else {
alert('statement 4 executed');
}
Related Tutorials
JavaScript Intermediate Tutorials - Lesson 3 - Conditional Statements