This site is mobile accessible. Press the "Tap Here" button to use a different font-size.


Smartphone icons created by Freepik - Flaticon

  • 5.3 JS Random

    Math.random() returns a random number between 0 (inclusive), and 1 (exclusive):

    Example 1: JS Math.random()
    Math.random();              // returns a random number

    Math.random() always returns a number lower than 1.

    JavaScript Random Integers

    Math.random() used with Math.floor() can be used to return random integers.

    Example 2: JS Math.floor(Math.random() * 10)
    Math.floor(Math.random() * 10);     // returns a random integer from 0 to 9
    Example 3: JS Math.floor(Math.random() * 11)
    Math.floor(Math.random() * 11);      // returns a random integer from 0 to 10
    Example 4: JS Math.floor(Math.random() * 100)
    Math.floor(Math.random() * 100);     // returns a random integer from 0 to 99
    Example 5: JS Math.floor(Math.random() * 101)
    Math.floor(Math.random() * 101);     // returns a random integer from 0 to 100
    Example 6: JS Math.floor(Math.random() * 10) + 1
    Math.floor(Math.random() * 10) + 1;  // returns a random integer from 1 to 10
    Example 7: JS Math.floor(Math.random() * 100) + 1
    Math.floor(Math.random() * 100) + 1; // returns a random integer from 1 to 100

    A Proper Random Function

    • As you can see from the examples above, it might be a good idea to create a proper random function to use for all random integer purposes.
    • This JavaScript function always returns a random number between min (included) and max (excluded):
    Example 8: JS Math.random() getRndInteger part 1
    function getRndInteger(min, max) {
      return Math.floor(Math.random() * (max - min) ) + min;
    }

    This JavaScript function always returns a random number between min and max (both included):

    Example 9: JS Math.random() getRndInteger part 2
    function getRndInteger(min, max) {
      return Math.floor(Math.random() * (max - min + 1) ) + min;
    }
    Navigate this module

    Eventually the navigation links, above, will be replaced by these << (previous) and >> (next) buttons below.



    JavaScript icons used in the buttons provided by ICONS8.COM. Smartphone icons created by Freepik - Flaticon