Creating random integers within a defined range using JavaScript

I need help with making a JavaScript function that picks random whole numbers between two values I set. Let’s say I have minValue = 10 and maxValue = 15, and I want the code to randomly give me any number from that range like 10, 11, 12, 13, 14, or 15. I’ve been trying different approaches but can’t get it to work properly. What’s the best way to do this? I’m looking for a solution that includes both the starting and ending numbers in the possible results. Any code examples would be really helpful since I’m still learning JavaScript basics.

Math.random() spits out a decimal between 0 and 0.999. Multiply that by (maxValue - minValue + 1) and you get 0 to just under 6 in your case. Math.floor() rounds down to integers 0-5, then adding minValue shifts everything to 10-15. I’ve used this tons of times - it’s solid. Just make sure your min and max values are actually integers or you’ll get weird results. Wrap it in a function for easy reuse: function randomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; }

hey! just use this: Math.floor(Math.random() * (maxValue - minValue + 1)) + minValue. the +1 is key so u include both ends. for ur range, it would be Math.floor(Math.random() * 6) + 10 to get 10-15.

Yeah, that formula works great, but watch out for a few things. I kept passing floats instead of integers when I started - it’ll work but give you weird decimal results. Also, Math.random() isn’t cryptographically secure, so use crypto.getRandomValues() if you need real security. For basic stuff though, Math.random() is fine. I always validate that min < max first, otherwise you’ll get confusing results. You’ll get the hang of it after using it a few times.