We have covered conditional statements, which test if a condition exists. Complex condtional statements test for more than one condition. For example:

  • the user is over 21 and is registered to vote  (userAge > 21 && userReg == true)
  • the car is of a Toyota but it is not red    (carModel == "Toyota" && carColor != "red")
  • the total is less than 20 or greater than 50  (total < 20 || total > 50)

 Complex conditional statements make use of comparison operators and logical operators.

Comparison Operators
OperatorNameResult
== equal returns true if the operands are of equal value
!= not equal returns true if the operands are not of equal value
=== strict equal returns true if the operands are equal and of the same type
!== strict not equal returns true if the operands are not equal and/or not of the same type
greater than returns true if the value of the left operand is greater than the value of the right operand
< less than returns true if the value of the left operand is less than the value of the right operand
>= greater than or equal to returns true if the value of the left operand is greater than or equal to the value of the right operand
<= less than or equal to returns true if the value of the left operand is less than or equal to the value of the right operand

 

Logical Operators
OperatorExampleNameDescription
&& condition1 && condition2 OR Returns true if both conditions are true
|| condition1 || condition2 AND Returns true if one or both conditions are true
! !condition1 NOT Returns true if the condition is NOT true

The comparison operators return true if that condition is met, the logical operators test if mutiple conditions are met.

aa-three-dots

Testing if more than one condtion is true

To test if more than one condition is true, you use the logical AND operator &&.

Say you were doing a survey for people that were over 40 AND they had a retirement fund. 

if (subjectAge > 40 && retFund = true) {
   // code goes here
}

aa-three-dots

Testing for an either or situation

To test if a certain condition is true OR another condition is true, you use the logical OR operator ||.

For example, you are testing that the pet owner owns either a cat OR a dog.

if (ownerPet == "cat" || ownerPet == "dog"){
    // code goes here
}

aa-three-dots

Checking that a condition is not true

You may need to filter out a certain condition, in this case you use the logical NOT operator !.

Say you want to be sure noone under the age of 18 is processed.

if (! applicantAge < 18){
    // code goes here
}

aa-three-dots

Using multiple logical operators

Is is possible to use a combination of logical operators in a statement.

Say you want the total of participants to be over 30 and under 100 but not equal to 65.

if (total > 30 && total < 100 && total != 65){
   // code goes here
}