I wanted to create global random variables, but when I used random() outside of all the functions, random() was not recognized.
A student Googled that I needed to use Math.random() in this case. Why is that?
Hi @rkotty,
Welcome to the forum!
Interesting remark! If you run it in the p5js web editor, you get the following error messages:
p5.js says:
[sketch.js, line 1] “random” is not defined in the current scope. If you have defined it in your code, you should check its scope, spelling, and letter-casing (JavaScript is case-sensitive).
More info: examples | p5.js
Did you just try to use p5.js’s random() function? If so, you may want to move it into your sketch’s setup() function.More info: why-cant-i-assign-variables-using-p5-functions-and-variables-before-setup
And the linked wiki page explains it very well:
In regular global mode, p5 variable and function names are not available outside
setup()
,draw()
,mousePressed()
, etc. (Except in the case where they are placed inside functions that are called by one of these methods.)
This works:
let randomValue;
function setup() {
createCanvas(400, 400);
randomValue = random(1, 100);
}
P5.js library automatically dumps its API in the global context only after it finds either callbacks setup() or draw() are present in the global context as well.
Therefore any code outside functions runs too early before that checking.
If you really need to access p5js properties earlier you can prematurely instantiate it via new p5;
as this sketch below does for color(), cos(), sin() and DEG_TO_RAD: