Random to initialize variables

I have a question. I’ve noticed that when I initialize variables with a value before setup(); or draw(); that it works for a string, boolean, number.

However, if I try to set that value to a random number using random() it will not work outside of setup(); or draw(). Why is it that functions do not work outside of setup() or draw()?

Any information would be appreciated.

1 Like

Welcome to the forum, @davidhurwich!

Technically, p5.js is not ready when that variable is initialized. So random() is not available to be called. If you take a look at the JavaScript console in your browser’s developer tools, you’ll probably see an error like ReferenceError: Can't find variable: random.

You could get a random number by using vanilla JavaScript instead: Math.random(). Or use this workaround:

new p5();

var boop = random(100);

function setup() {
    createCanvas(100, 100);
}

function draw() {
    background(255, 0, boop);
}

Source: Why can’t I assign variables using p5 functions and variables before setup()?

4 Likes
2 Likes