Skip to content
Advertisement

Can anyone explain the below code logic in javascript? [closed]

In some coding practice websites, I found below assignment operation for generating a random whole number that falls within a range of two specific numbers.

To do this, we’ll define a minimum number min and a maximum number max.

Here’s the formula we’ll use. Take a moment to read it and try to understand what this code is doing:

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

This formula is bit ambiguous to me. Could anyone please explain the logic.

Advertisement

Answer

Let’s break this:

  1. First lets look at Math.random(). According to here

The Math.random() function returns a pseudo-random number in the form of a floating point number in the range from 0 – 1 (including 0, but not 1)

  1. Multiply it by (max - min + 1) will give you offset in the range between min and max and will make sure you won’t exceed this limit.
  2. Adding + min will make sure you get the shifting from [0 to offset] to [min to offset + min] which we said is limited by max.
  3. Finally Math.floor to make it integer number instead of float (its floor and not Math.ceil because the original Math.random() is not including the 1).
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement