An important part of any programming language is the ability to make decisions, or choices. The if-else construct is the most basic and common method of decision making.
The syntax of the if-else construct is:
where:
- condition
- is a logical condition which evaluates to either true or false
- action-one
- is the set of JavaScript commands to perform if the condition evaluates true
- action-two
- is the set of JavaScript commands to perform if the condition evaluates false
NOTES:
Operator | Condition |
---|---|
== | equality |
!= | inequality |
> | greater than |
< | less than |
>= | greater than or equal to |
<= | less than or equal to |
if (a == b)
Logical Operator | Condition |
---|---|
&& | and |
|| | or |
! | not |
Examples:
if-else Example One
This example will use the following if statement to decide if the number entered is equal to 10. If the number is equal to 10, the background colour of this document will change to green, otherwise it will change/stay red.
The function that performs this test is:
Click Here to start example one.
This example will use the following 'if' statement to decide if the number entered is equal to 10. If the number is equal to 10, the background colour of this document will change to green, otherwise it will change/stay red. In both cases, an alert box is displayed to inform the user of the results of the test. This example illustrates the use of multiple lines of code for the action of an if-else branch.
Click Here to start example two.
This example will use the following 'if' statement to decide if the number entered is equal to 10 and the user entered their name. If both conditions are true, the background colour of this document will change to green, otherwise it will change/stay red. In both cases, an alert box is displayed to inform the user of the results of the test. This example illustrates the use of multiple lines of code for the action of an if-else branch and a compound condition.
Click Here to start example three.
When the results of a condition test is to be one of two possible values, a condition statement may be more practical than an if-else construct. The condition statement has the following syntax:
where:
- condition
- is a logical condition which evaluates to either true or false
- true-value
- is the value to return if the condition evaluates true
- false-value
- is the value to return if the condition evaluates false
Condition statements may be used wherever a value is required, such as in an assignment statement or a return statement. For example:
The following code sets the value of status depending upon the age entered by the user.
Click Here to start condition statement example.