skip to Main Content

Math.random()

I tried changing numbers, plus i also tried removing and re-adding math floor but the outcome was still the same. It’s supposed to give different number every time but in my case it’s only giving one number as an output no matter how many times i write the code.

My code is

var thisIsNew = Math.floor(Math.random() * 6);

3

Answers


  1. If you generate a single random number and store it in a variable, the contents of the variable won’t change across different outputs of the same unchanged variable.

    Instead what you need to do is make a function that generates random numbers the way you like, and call that function multiple times:

    RND_MULTIPLIER = 6;
    
    function myRandom() {
      return Math.floor(Math.random() * RND_MULTIPLIER);
    }
    
    console.log(myRandom());
    console.log(myRandom());
    console.log(myRandom());
    

    will print 3 freshly generated random numbers.

    Login or Signup to reply.
  2. thisIsNew is a variable which is defined and initialized via this line:

    var thisIsNew = Math.floor(Math.random() * 6);
    

    At this point you compute a randomized number between 0 and 1, multiply it with 6, so it will be between 0 and 6 and floor it, so it will be 0, 1, 2, 3, 4, 5.

    Once the computation is over, this value is assigned to your newly created variable of thisIsNew, which, from that point onwards will have this value until you change it. So, when you later on refer to thisIsNew, without changing its value, it will be the same. You can compute it again when needed.

    A neat way to do so is to have a randomization function, like

    function randomize(seed = 6) {
        return Math.floor(Math.random() * 6);
    }
    
    console.log(randomize());
    console.log(randomize());
    console.log(randomize());
    Login or Signup to reply.
  3. Usually a variable with a primitive value does not change the value. To get a different value, you need a function (callable value) and this returns the result of a function. Another solution could be an object with a property getter.

    You could use an object, here window and create a property with a getter.

    Object.defineProperty(window, "randomize", {
        get() {
            return Math.random();
        }
    });
    
    console.log(randomize);
    console.log(randomize);
    console.log(randomize);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search