Skip to main content

if, else-if, else

Using else-if allows us to test a new condition if the previous condition is false:

if (condition1) {
// executed if condition1 is true
} else if(condition2) {
// executed if condition1 is false and condition2 is true
} else {
// executed if condition1 is false and condition2 is false
}

The following flowchart example describes the else-if control statement:

if, else-if, else

if, else-if, else

  1. We start with the variable age with a value of 25.
  2. Then we have a condition to check if the age is less than or equal to 5:
    • If age <= 5 resolves true (yes), then we will print Infant 0-5 years old.
    • If age <= 5 resolves false (no), we will check the next condition.
  3. The next condition checks if the age is less than 18:
    • If age < 18 resolves true (yes), then we will print Teenager 6-17 years old.
    • If age < 18 resolves false (no), we will check the last condition.
  4. The last condition checks if the age is less than 50:
    • If age < 50 resolves true (yes), then we will print Adult 18-49 years old.
    • If age < 18 resolves false (no), then we will print Elderly 50 or more years old.
  5. The program continues...

Let's run the code of DartPad:

After running in DartPad, Adult 18-49 years old is printed in the console because the third condition was true. You can try changing the value of age to a value lower than 18. What is the result?