Random() vs. Math.random() in p5js

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?

1 Like

Hi @rkotty,

Welcome to the forum! :wink:

Interesting remark! If you run it in the p5js web editor, you get the following error messages:

:cherry_blossom: 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).

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);
}
1 Like

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:

2 Likes