if....else constructS2C Home « Statements « 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.

Syntax

Signature Description
Simple if
if (condition) {
   statement1
}
Execute statements in statement1 if condition expression evaluates to true.
if....else
if (condition) {
   statement1
} else {
   statementN
}
Execute statements in statement1 if condition expression evaluates to true, otherwise execute statements in statementN.
Multiple if....else
if (condition) {
   statement1

} else if (condition2) {
   statement2

} else if (condition3) {
   statement3
   ...
} else {
   statementN
}
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
conditionAn expression that evaluates to true or false.
statement1Statements to execute when condition expression evaluates to true.
condition2An expression that evaluates to true or false.
statement2Statements to execute when condition2 expression evaluates to true.
condition3An expression that evaluates to true or false.
statement3Statements to execute when condition3 expression evaluates to true.
statementNStatements 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');
}

Press the button below to action the above code:


Related Tutorials

JavaScript Intermediate Tutorials - Lesson 3 - Conditional Statements

go to home page Homepage go to top of page Top