JS Tutorial – Lots of Ways to Use Math.random() in JavaScript


Rengga Dev Math.random() is an API in JavaScript. It is a function that gives you a random number. The number returned will be between 0 (inclusive, as in, it’s possible for an actual 0 to be returned) and 1 (exclusive, as in, it’s not possible for an actual 1 to be returned).

Math.random(); // returns a random number lower than 1

This is incredibly useful for gaming, animations, randomized data, generative art, random text generation, and more! It can be used for web development, mobile applications, computer programs, and video games.

<p>Random number between 0 and 1.</p>
<button onclick="myFunction()">Try It</button>
<p id="randomnumber"></p>
<script>
  function myFunction() {
    document.getElementById("randomnumber").innerHTML = Math.random();
  }
</script>

<p>Random integer between 1 and 10 (both included).</p>
<button onclick="document.getElementById('demo').innerHTML = getRndInteger(1,10)">Try It</button>
<p id="demo"></p>
<script>
  function getRndInteger(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }
</script>

<!-- reference: w3schools -->


Whenever we need randomization in our work, we can use this function! Let’s look at eight different ways we can use it. These examples are all from different authors doing something interesting with this API.

Nandemo Webtools

Leave a Reply