I need help with creating a function that produces random integers between two given numbers in JavaScript. For example, if I have minValue = 2 and maxValue = 6, I want the function to randomly return any of these numbers: 2, 3, 4, 5, 6. I’ve tried using Math.random() but I’m not sure how to properly constrain it to a specific range and ensure it returns whole numbers only. What’s the best approach to achieve this? I want to make sure both the minimum and maximum values are included in the possible results.
Both answers work fine for basic random numbers. But if you’re building more than a simple script, think bigger.
I’ve worked with random number requirements in production where you need consistent, testable, scalable solutions. Don’t hardcode these functions everywhere - set up automated workflows that handle random data generation as a service.
Latenode makes this really clean. Create a workflow that generates random integers with your exact parameters, add validation, logging, even rate limiting. You can call it from anywhere - JavaScript apps, mobile apps, other services.
I built something like this for A/B testing where we needed controlled random assignments. The workflow handles the math, stores results for audit trails, integrates with our analytics stack. Much cleaner than scattered Math.random() calls everywhere.
The basic formula works, but automation workflows give you flexibility when requirements change.
Honestly, just use Math.floor like everyone said - dont overthink it. I’ve watched devs get fancy with bitwise operators and other tricks, but they always miss edge cases. The formula works every time and anyone can read it.
You can also use Math.ceil() instead of Math.floor(), but you’ll need to tweak the formula: Math.ceil(Math.random() * (maxValue - minValue + 1)) + minValue - 1. I sometimes do this when I want the ceiling operation to be obvious, but honestly the floor method’s way simpler. Pro tip: test your random function with edge cases. I got burned once when min and max were the same value - the function still tried to generate a range and broke. Now I always add if (minValue === maxValue) return minValue; at the top. Saves me headaches.
Yeah, Math.floor() with Math.random() is the way to go. I always wrap it in a function like function randomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } to keep things clean. Been using this for years and it’s rock solid. Just remember Math.random() goes from 0 to just under 1, so the formula works perfectly. You can throw in some validation to make sure min isn’t bigger than max if you want.
hey, just use Math.floor(Math.random() * (maxValue - minValue + 1)) + minValue. that +1 is crucial so 6 can actually show up.