Js Random in JavaScript
? JavaScript Random Numbers
In JavaScript, you generate random numbers using the built-in Math.random() function.
Math.random()
Returns a floating-point number between 0 (inclusive) and 1 (exclusive).
console.log(Math.random()); // e.g., 0.48216367170458025Generate Random Number in a Range
To get a random integer between two values (inclusive), use this formula:
function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min;}// Example: random integer between 1 and 10console.log(getRandomInt(1, 10));Generate Random Float in a Range
function getRandomFloat(min, max) { return Math.random() * (max - min) + min;}// Example: random float between 1.5 and 5.5console.log(getRandomFloat(1.5, 5.5));Example: Random Color Generator
function getRandomColor() { const r = getRandomInt(0, 255); const g = getRandomInt(0, 255); const b = getRandomInt(0, 255); return `rgb(${r},${g},${b})`;}console.log(getRandomColor()); // e.g., rgb(123,45,67)Summary
Math.random()returns float ?0 and <1Use multiplication and rounding to get desired range
Want me to show how to shuffle an array randomly or generate random IDs?