JS Tutorial



JS RANDOM


JavaScript Math.random() ๐ŸŽฒ

The Math.random() method returns a pseudo-random floating-point number between 0 (inclusive) and 1 (exclusive).

Math.random(); // Example: 0.423512837
  

๐Ÿ”ข Generate Random Integers

You can use Math.random() with Math.floor() to create random integers in a range.

  • 1 to 10: Math.floor(Math.random() * 10) + 1
  • 0 to 99: Math.floor(Math.random() * 100)
  • Custom range (min to max):
    Math.floor(Math.random() * (max - min + 1)) + min
// Random number between 1 and 10
let num = Math.floor(Math.random() * 10) + 1;
console.log(num);

// Between 50 and 100
let custom = Math.floor(Math.random() * (100 - 50 + 1)) + 50;
console.log(custom);
  

๐ŸŽฎ Live Example: Random Number in Range

Enter min and max

๐ŸŽฒ Simulating Dice Roll

// Roll a 6-sided die
let roll = Math.floor(Math.random() * 6) + 1;
console.log("Dice roll:", roll);
  

๐Ÿ“Œ Use Cases

  • Games: Dice, random choices, spawning objects
  • Random backgrounds, colors, images
  • Shuffling or picking random array items
Note: JavaScriptโ€™s Math.random() is not cryptographically secure. Use crypto.getRandomValues() for secure randomness.

๐ŸŒŸ Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review