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?

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.

1 Like

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

this execute before any mouse event happens

function draw() {
  if (mouseIsPressed === true) {
    line(mouseX, mouseY, pmouseX, pmouseY);

so you get this error

Uncaught ReferenceError: currentColor is not defined 

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