Spicy Yoghurt | Last updated: 6 Juli 2019 | JavaScript tutorial

How to generate random numbers

Learn how to apply Math.random() to generate random numbers in JavaScript. Get numbers between a certain range and generate random integers.

Using the basic Math.random() function

In JavaScript you can access the Math object from anywhere in your code. It contains helpful mathematical functions, including the random() function. This function generates a floating-point number between 0 and 1 (including 0, excluding 1) and can be used as a base for calculating other random numbers.

You can use the basic random() function on the Math object like this:

            Math.random();

        //Possible output
        0.8974465382241915
        0.2958720891619725
        0.006575835239084449
        0.9456002830285726
        

Get a random number between two values

The results of the random() function can be scaled to generate other types of random values.

You can use the following code to generate a random floating-point number between a min and max value. (including min, excluding max)

        function getRandomNumber(min, max) {
          return Math.random() * (max - min) + min;
        }
        

        getRandomNumber(0, 10)

        //Possible output
        3.8690255118743275
        0.15779814409071835
        7.52113864188321
        9.401215911876138
            

Get a random integer within a range

In some cases you'll need an integer value instead of a floating point. You can use the next function to generate random integers. This time, the results will include both the min and the max.

        function getRandomInt(minInt, maxInt) {
          return Math.floor(Math.random() * (maxInt - minInt + 1)) + minInt;
        }
        

        getRandomInt(0, 10)

        //Possible output
        6
        2
        10
        0
            

Leave a comment