Confusing global variable behaviour

I made this drawing app utilizing the p5js library. It wouldn’t work for the longest time until I gave the global variable a value. Why does this code work with the defined global variable value and not without the value?

https://codepen.io/edubz/pen/wvoRYYy

currentColor will be undefined inside the draw function until it has been set to something inside one of the on callbacks. Which means stroke(currentColor) is called with an undefined value.

https://p5js.org/reference/#/p5/draw

1 Like

but wouldn’t currentColor be set during one of the mouseclick events?

this execute before any mouse event happens

function draw() {
  stroke(currentColor);
  console.log(currentColor);
  if (mouseIsPressed === true) {
    line(mouseX, mouseY, pmouseX, pmouseY);
  }
}

so you get this error

Uncaught ReferenceError: currentColor is not defined 
 at https://cdpn.io/cp/internal/boomboom/pen.js?key=pen.js-38a923ae-78aa-5def-09eb-eb788e4b3821:43

and your project doesn’t work

1 Like

ok, true. currentColor is undefined to begin with. but after you click a color, why would the variable still be undefined? I dont understand why a value initially has to be set to the variable in order for another value to populate it later.

the JavaScript stops working with that error, so there is no “after”

1 Like

ok, I see. Thank you for your help

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.