p5.js Beginner Article 3

Conditionals & Logic

if/else, boolean logic, and state machines — making your sketch react intelligently.

⏱ 16 min read conditionals if/else logic boolean state

if / else if / else

if (condition) {
  // runs when condition is true
} else if (otherCondition) {
  // runs when first is false and this is true
} else {
  // runs when all above are false
}

Real example — colour the circle based on mouse position:

function draw() {
  background(20);
  noStroke();

  if (mouseX < width / 3) {
    fill(255, 80, 80);   // left third — red
  } else if (mouseX < (width / 3) * 2) {
    fill(80, 255, 80);   // middle third — green
  } else {
    fill(80, 80, 255);   // right third — blue
  }

  circle(width / 2, height / 2, 100);
}

Comparison operators

Operator Meaning
=== Strictly equal
!== Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal

Always use === (triple equals) in JavaScript, not ==. The double equals does type coercion and can give surprising results.

Boolean operators

Combine conditions with && (AND), || (OR), and ! (NOT):

// AND — both must be true
if (mouseX > 100 && mouseX < 500) { ... }

// OR — at least one must be true
if (mouseIsPressed || keyIsPressed) { ... }

// NOT — inverts the condition
if (!mouseIsPressed) { ... }

The ternary operator

A compact if/else for simple assignments:

let fillColor = mouseIsPressed ? color(255, 100, 50) : color(50, 100, 255);
fill(fillColor);

Equivalent to:

let fillColor;
if (mouseIsPressed) {
  fillColor = color(255, 100, 50);
} else {
  fillColor = color(50, 100, 255);
}

Boolean flags — toggles and modes

Store state in boolean variables:

let showGrid     = true;
let paused       = false;
let trailEnabled = true;

function keyPressed() {
  if (key === 'g') showGrid     = !showGrid;
  if (key === ' ') paused       = !paused;
  if (key === 't') trailEnabled = !trailEnabled;
}

function draw() {
  if (!trailEnabled) background(20);

  if (showGrid) drawGrid();

  if (!paused) {
    updateAll();
  }

  drawAll();
}

State machines

A state machine holds the sketch in one of several named modes, with transitions between them:

// States: 'idle', 'drawing', 'playback'
let state = 'idle';
let points = [];

function draw() {
  background(20);

  if (state === 'idle') {
    drawIdleScreen();
  } else if (state === 'drawing') {
    drawRecordingOverlay();
    if (mouseIsPressed) {
      points.push({ x: mouseX, y: mouseY });
    }
  } else if (state === 'playback') {
    drawStoredPath();
  }
}

function keyPressed() {
  if (key === 'd') state = 'drawing';
  if (key === 'p') state = 'playback';
  if (key === 'i') { state = 'idle'; points = []; }
}

function drawStoredPath() {
  stroke(100, 200, 255);
  strokeWeight(2);
  noFill();
  beginShape();
  for (let pt of points) vertex(pt.x, pt.y);
  endShape();
}

Checking distance and proximity

Conditional + dist() for interactive elements:

let circles = [
  { x: 150, y: 200, r: 40, label: 'A' },
  { x: 300, y: 200, r: 55, label: 'B' },
  { x: 460, y: 200, r: 35, label: 'C' }
];

function draw() {
  background(20);

  for (let c of circles) {
    let hovering = dist(mouseX, mouseY, c.x, c.y) < c.r;

    fill(hovering ? color(255, 200, 50) : color(60, 80, 140));
    stroke(hovering ? color(255, 220, 100) : color(40, 60, 120));
    strokeWeight(2);
    circle(c.x, c.y, c.r * 2);

    fill(hovering ? color(20) : color(200));
    noStroke();
    textAlign(CENTER, CENTER);
    textSize(16);
    text(c.label, c.x, c.y);
  }
}

switch / case

Useful when checking one variable against many values:

let mode = 1;

function draw() {
  background(20);
  noStroke();

  switch (mode) {
    case 1:
      fill(255, 100, 50);
      circle(width / 2, height / 2, 100);
      break;
    case 2:
      fill(50, 255, 100);
      rect(width / 2 - 50, height / 2 - 50, 100, 100);
      break;
    case 3:
      fill(100, 50, 255);
      triangle(width / 2, height / 2 - 60, width / 2 - 60, height / 2 + 40, width / 2 + 60, height / 2 + 40);
      break;
    default:
      fill(150);
      text('Unknown mode', width / 2, height / 2);
  }
}

function keyPressed() {
  let n = parseInt(key);
  if (!isNaN(n) && n >= 1 && n <= 3) mode = n;
}

Key takeaways

  • if / else if / else branches code based on conditions
  • Use === for equality checks (strict), never ==
  • &&, ||, ! combine boolean conditions
  • Boolean flags (let paused = false) are the simplest form of state
  • State machines (let state = 'idle') handle complex multi-mode behaviours
  • switch is clean when one value maps to many possible behaviours