Avatar ·

How to generate a random integer in a given range in JavaScript?

Hi everyone! I'm new to JavaScript and can't figure out how to generate random integers in a specific range. I know about the Math.random() function, which returns a random number from 0 (inclusive) to 1 (exclusive). But I need to get integers, for example, from 5 to 10 inclusive.\n\nI tried writing this code:\n
function getRandomNumber(min, max) {\n  return Math.floor(Math.random() * max) + min;\n}\n
\nBut it doesn't work correctly: sometimes it gives numbers greater than max, and sometimes less than min. For example, when calling getRandomNumber(5, 10), I got 14 or 3. What is my mistake? How to correctly write a function that will return a random integer in the range [min, max] (including both boundaries)?\n\nI would be grateful for a detailed explanation with a working example.