How to generate a random number in a given range in javascript

published: 29 Sep 2022

2 min read

We have seen many versions of generating random numbers. Here is a simple one. 

Input: 2 cardinal numbers

Output: a random cardinal number in the range [min, max] inclusive

const getRandomNumberInRange =(min, max)=> {
 min = Math.ceil(min);
 max = Math.floor(max);
 return Math.floor(Math.random() * (max - min + 1)) + min;
}
getRandomNumberInRange(3, 20);

How to generate a random number in a given range  in javascript | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript
Check out what's on in the tag: nodejs, javascript, numbers

TipsAndTricksta

I love coding, I love coding tips & tricks, code snippets and javascript