Boolean Logic
George Boole (1815-1864) wanted everything to be either true or false, with nothing in between. And so, he formalized Boolean logic: a way of computing with binary truth values, i.e. true or false.
The word boolean refers to a variable that can only have two possible values: true (1) or false (0).
Comparison operators
The results of comparisons – checking equality or inequality – are booleans. For example:
equality (==)
1 == 1
1 == 2
inequalities (<, >, <=, >=)
1 > 0
5 < 2
5 > 5
5 >= 5
Logical operators
Boolean logic is built using three basic operations that combine and act on booleans: and, or, and not.
and (&&)
true && true
false && false
true && false
or (||)
true || true
false || false
true || false
not (!)
!true
!false
These operators don't only work on literal true and false symbols. You can substitue in any expressions that evaluate to true or false, and you can combine multiple operators:
(12 > 10) && (3 > 5)
("x" == "x") && !(0 > 1)
Conditional Statements
Conditional statements check if a given condition is true or false to determine what code to execute. Conditional statements start with if and may also include fallback cases using else.
if
if (A) {
}
else
if (A) {
} else {
}
else if
if (A) {
} else if (B) {
} else {
}
State Variables
State variables are booleans that keep track of the “state” of a system, e.g., whether a condition is true or false. State variables are useful tools for referencing the same condition in multiple places. Here is an example in p5.js:
let displayQ = false;
function mousePressed () {
displayQ = !displayQ;
}
draw() {
if (displayQ) {
rect(50, 50, 100, 200);
}
}
Note: I usually add a Q to the end of my state variable names to indicate that their value is either “true” or “false” (i.e., the answer to a true or false Question)
Practice
Create p5.js sketches that have the following behaviors:
-
displays a rectangle only when the mouse is being held down
(hint)/span>
-
displays a rectangle only when the mouse is located on the bottom right half of the canvas
-
displays a rectangle only after the mouse has been clicked 10 times
(hint)/span>
-
displays a black rectangle that turns red if the mouse has been clicked once, blue if the mouse has been clicked twice, and green if the mouse has been clicked three or more times
-
displays a rectangle that toggles between being red and white any time the left side of the canvas is clicked
Bonus:
-
create a rectangular button that logs “you clicked me N times” in the console whenever the rectangle is clicked, where N is the number of times the button has been clicked
-
create a rectangle with a “drag-and-drop” effect
-
write your own description (like the ones above) of a simple sketch that updates based on a conditional, then have a classmate figure out how to code it
Once you have attemped the exercises on your own, you can see sample solutions here. Note: there may be many different correct solutions! These are just examples.