</> Code Corner

JavaScript · JS Tutorial · Lesson 25

JS Random

Random numbers and random integers.

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

Example

<p id="demo"></p>
<button onclick="roll()">Roll the dice</button>
<script>
function getRndInteger(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
function roll() {
  document.getElementById("demo").innerHTML =
    "Dice: " + getRndInteger(1, 6) + " | 0-99: " + Math.floor(Math.random() * 100);
}
roll();
</script>
Tip: Math.floor(Math.random() * (max - min + 1)) + min returns a random integer between min and max, both included.

Keep reading “JS Random”

Sign up to read the full lesson, try every example in the live editor, and take the 5-question quiz.

Chat with us 👋