JavaScript

JavaScript is a high-level, interpreted programming language that is widely used for web development. Initially designed as a client-side scripting language, it runs directly in web browsers, enabling dynamic and interactive user experiences. JavaScript can now be used for server-side development as well.

JavaScript Random

8 April 2025 | Category:

JavaScript provides a built-in method to generate random numbers using the Math.random() function.

This is useful in games, simulations, animations, and many other situations where you want unpredictability.


âś… Basic Syntax

Math.random();

Output:

A random floating-point number between 0 (inclusive) and 1 (exclusive).

console.log(Math.random()); 
// Example: 0.7354323562

📌 Generate Random Whole Numbers

Since Math.random() returns a decimal, we combine it with Math.floor() to get whole numbers.


🔢 Random Number Between 0 and 9:

const num = Math.floor(Math.random() * 10);
console.log(num); // 0 to 9

🔢 Random Number Between 1 and 10:

const num = Math.floor(Math.random() * 10) + 1;
console.log(num); // 1 to 10

🔢 Random Number Between Min and Max

Use this reusable function:

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

console.log(getRandom(50, 100)); // Random number from 50 to 100

🎯 Use Cases

  • Randomizing quiz questions
  • Creating dice rolls
  • Generating random colors
  • Lottery systems
  • Animations with randomness

🎨 Example: Generate Random RGB Color

function getRandomColor() {
  const r = Math.floor(Math.random() * 256);
  const g = Math.floor(Math.random() * 256);
  const b = Math.floor(Math.random() * 256);
  return `rgb(${r}, ${g}, ${b})`;
}

console.log(getRandomColor()); // e.g., rgb(12, 200, 150)

⚠️ Note

  • Math.random() is not truly random; it’s pseudo-random based on an algorithm.
  • It’s good for most tasks, but not secure for cryptography or passwords.

đź§  Summary

  • Math.random() generates decimals between 0 and 1.
  • Combine with Math.floor() to get whole numbers.
  • Use custom formulas to define your own random number ranges.