What does this piece of javascript code do?

Math.floor(Math.random() * (max - min + 1)) + min

Math.floor() = rounds the number down
Math.random() = returns a random number
max and min are variables that are undefined, but I’ll give you an example below.

var max = 4;
var min = 1;
mathrandom() //This would not be in the code but in the example let's use .55

So this is out it evaluates step by step.

  1. 4 - 1 + 1 = 4
  2. .55 * 4 = 2.2
  3. 2.2 + 1 = 3.2
  4. Math.floor(3.2) = 3
1 Like

Math.random() produces a number between 0 and 1 (including 0 but not 1)

So for example 0.63729 or 0.345

Math.floor() is a function returns the closest integer that is less than whatever you give it

Math.floor(2.98754) // 2
Math.floor(12.8) // 12

So if you put values in for min and max, what do you get?

1 Like