Why would we need math.random and math.floor in Javascript?

Yeah, I just came back from learning the two and I have 2 questions, why would we use math.random and math.floor in Javascript? Also I am still confused about the two and their functions

To give you a simple answer; Instead of writing the whole code yourself about generating math results which may take up a lot of lines, you only use one line when using the Math library.

The Math.random() function returns a floating-point, pseudo-random number that’s greater than or equal to 0 and less than 1, with approximately uniform distribution over that range — which you can then scale to your desired range. The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user.

The Math.floor() function always rounds down and returns the largest integer less than or equal to a given number.

2 Likes

I guess you could combine these to generate a random integer.

function randInt(smallest, largest) {
  const widthPlus1 = largest - smallest + 1;
  return Math.floor((Math.random() * widthPlus1) + smallest);
}