Home 11: Logical operators
Content
Cancel

11: Logical operators

To build more complex conditions you can combine single conditions into a combined one with logical operators. There are two logical operators available, the and operateor (&&) and the or operator (||).

Let us have a look at an example to make it more clear. In this example we want to change the color of the background from white to red if the mouseX position is between 200 and 400 pixels. Otherwise the background should be white.

1
2
3
4
5
6
7
function draw() {
  if (mouseX >= 200 && mouseX <= 400) {
    background(255, 0, 0);
  } else {
    background(255, 255, 255);
  }
}

Because of the and operator, only if both conditions are true, the action-block of the if-statement is executed.

You can combine as many conditions with each other as you like and you can use brackets to group them logically, like in math calculations.

Let us have a look at another example with the or operator.

1
2
3
4
5
6
7
function draw() {
  if (mouseX < 200 || mouseX > 400) {
    background(255, 255, 255);
  } else {
    background(255, 0, 0);
  }
}

If the mouseX position is smaller than 200 or bigger than 400 pixels the background is white. Otherwise the background will be red.

Notice that this example is another solution to the same problem as above. It is just written in a different way and both solution fulfill the requirements.

Note: In this example it would not be possible to replace the or operator with the and operator, because it would never be true. The mouseX position can not be smaller than 200 and larger than 400 pixels at the same time.

This post is licensed under CC BY 4.0 by the author.