WEEK: 7
Active: February 21st - February 27th
Work Due: February 28th @ 9:00AM

‘Else If’ Statements

Let’s keep deep diving on conditional flow for our program structure. So far, we have looked at if statements, where if a input parameter evaluates to true the first function block is executed, else the second function block (which follows the else keyword) is executed.

There is also the possibility of including addition conditional tests in an if statement using else if statements.

An else if statement looks like the following;

if( someConditionCheck ) {
    // function block 1
    // executed if the above returns 'true'
} else if ( aDifferentConditionCheck ) {
    // function block 2
    // executed if the 'else if' condition is true
} else {
    // function block 3
    // executed if all 'if, else if' statements are 'false'
}

This conditional flow program structure can be used to construct more advanced programs!

Example

Let’s look at an example. Say we wanted to set the background of the canvas to one of 3 colors, depending on the mouse X (mouseX) position. To do this, we could use the else if statement, and check by region.

  • In our first conditional check, we would need to check if the mouse X position, is less than one-third of the canvas width.
    • if( mouseX < width * 1/3 ) {}
  • In the second conditional check, we could check if the mouse X position is less than two-thirds of the canvas width. This would use the else if() syntax.
    • else if( mouseX < width * 2/3 ) {}
    • This works because if the first condition (mouseX < width*1/3) is true, the rest of the conditional statement will be “skipped”, so this condition would never be checked.
  • Finally, if both of the above return false, we can assume the mouse is greater than two-thirds of the canvas width.
    • else {}
[ Code Download ] [ View on GitHub ] [ Live Example ]

Previous section:
Next section: