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!
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.
if( mouseX < width * 1/3 ) {}
else if()
syntax.
else if( mouseX < width * 2/3 ) {}
mouseX < width*1/3
) is true, the rest of the conditional statement will be “skipped”, so this condition would never be checked.else {}
[ Code Download ] | [ View on GitHub ] | [ Live Example ] |