p5.js Conditionals
Conditions in a programming language are instructions that direct the flow of a program. This works a bit like rail traffic: a train travels on a rail until it hits a switch, then the train changes its direction of travel. Conditions, therefore, change the course of a program. But how is the direction actually decided? The answer to this is logical operations based on the boolean logic (remember the logic gates exercise?).
Â
We use logical operations in everyday life, here are some examples:
When I'm hungry or thirsty, I go to the kitchen and get something
If I have enough money and I have time, then I'll make a trip to India
Â
In p5.js programming language the spelling is different but the logic behind it remains the same.
equal to ===
not equal !=
greater than >
less than <
greater than or equal to >=
less than or equal to <=
logical And &&
logical Or ||
In code it looks like this:
var x = 10;
if(x === 10)
{
print("x is the same as 10");
}
else
{
print("x is not the same as 10");
}
The code can almost be read out as intelligible language: If x is 10, write "x is equal to 10", if not then write "x is not equal to 10".
The syntax of a condition is always:
if([boolean expression])
{
// code that will be executed if the answer is true
}
else
{
// code that will be executed if the answer is false
}
With booleans you can include the variable without using the operators:
let x = true;
// Testing if a boolean value is "true"
if (test) {
stroke(0);
point(width / 3, i);
}
// Testing if a boolean value is "false"
// The expression "if(!test)" is equivalent to "if(test == false)"
if (!test) {
stroke(255);
point(width / 4, i);
}
If the first condition is false, we can test new condition with else if. We can keep doing this indefinitely.
For the multiple alternative cases, there is also the switch statement:
ExerciseÂ
Program a drawing app. The colour can be changed with the buttons '1' - '5'. The left mouse button draws and the right mouse button erases the drawing.
Â