JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JS Random


📘 JavaScript Math.random()Generating Random Numbers

The Math.random() method returns a pseudo-random floating-point number in the range:

0 ≤ Math.random() < 1

📌 It never returns exactly 1, only up to 0.999....


🔹 Syntax

Math.random();

Returns a floating-point number between 0 (inclusive) and 1 (exclusive).


🔹 Use Cases

Task Example
Random decimal 0–1 Math.random()
Random decimal 0–10 Math.random() * 10
Random integer 0–9 Math.floor(Math.random() * 10)
Random integer 1–10 Math.floor(Math.random() * 10) + 1
Random integer between min & max Math.floor(Math.random() * (max - min + 1)) + min

🔹 Random Integer Between Two Values

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

console.log(getRandomInt(1, 100)); // Random int between 1 and 100

🔹 Random Decimal Between Two Values

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

console.log(getRandomFloat(5.5, 10.5)); // e.g., 7.2341

🔹 Common Pitfalls

  • Math.random() returns a decimal, not an integer.

  • Always use Math.floor() or Math.round() to get whole numbers.

  • Always add +min to shift the range correctly.


Practice Questions

Q1. How do you generate a random floating-point number between 0 and 1 using Math?

Q2. How do you create a random integer between 0 and 9 using Math.random() and Math.floor()?

Q3. How do you generate a random number between 1 and 100 using a custom function?

Q4. What is the purpose of Math.floor() in the expression Math.floor(Math.random() * 10)?

Q5. How do you generate a random floating-point number between 5.5 and 10.5?

Q6. Write a function that returns a random number between any two given integers, inclusive.

Q7. What happens if you forget to add +min when generating a random number in a custom range?

Q8. How do you create a random number generator for a dice roll (1 to 6)?

Q9. How do you ensure that the result of Math.random() never equals 1?

Q10. How can you generate a random number that simulates a coin toss (Head or Tail)?


JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top