I need help understanding the math.random example in event module

in the first example of the math.random in the event module of JS, there is

const btn = document.querySelector('button');

function random(number) {
  return Math.floor(Math.random() * (number+1));
}

btn.onclick = function() {
  const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
  document.body.style.backgroundColor = rndCol;
}

i know math.random returns a floating point number between 0 and 1 and math.floor is there to make it whole number but is it that * (number+1) takes in the number passed by the rgb, then adds it to one making it 256, then multiplies it by any number generated by math.random. which will eventually become a whole number through the math.floor method

Hi @Nebula and welcome to the community :wave:

Your explanation is pretty much right. There’s one important thing to know about the boundaries of Math.random(): 0 is included, but 1 is excluded. When reading code with Math.random() I always think about a number from 0 to slightly less than one. Let’s look at the single steps of our code when having an input of 255:

Math.floor(Math.random() * (number+1))
// Replace number with 255
Math.floor(Math.random() * (255+1))
// Add 1
Math.floor(Math.random() * 256)
// Replace Math.random with "0 to 0.99"
// (0.99 isn't the exact value. It's just to think about it easily)
Math.floor((0 to 0.99) * 256)
// Multiply the range with 256
// (again, not an exact value for the upper bound)
Math.floor(0 to 255.99)
// Rounding down to the next integer
0 to 255

We now see that we get a whole number between 0 and 255 as return value of our random() function which is indeed the correct range for color values.

I hope that helps. Feel free to ask more questions. I’m happy to help :blush:

Michael

2 Likes