- Related Questions & Answers
- Generating n random numbers between a range - JavaScript
- Outputting a random number that falls in a certain range in JavaScript
- Generating random number in a range in C
- How to create a random vector for a range of values in R?
- Java Program to create random BigInteger within a given range
- How to return a random number between 0 and 199 with JavaScript?
- How to return a random number between 1 and 200 with JavaScript?
- How to generate a random number in JavaScript?
- How to get a pseudo-random number between 0 and 1 in JavaScript?
- Generate n random numbers between a range and pick the greatest in JavaScript
- How to generate random whole numbers in JavaScript in a specific range?
- Armstrong numbers between a range - JavaScript
- How can I generate random number in a given range in Android?
- Random whole number between two integers JavaScript
- Get Random value from a range of numbers in JavaScript?

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Our job is to create a function, say createRandom, that takes in two argument and returns a pseudorandom number between the range (max exclusive).

The code for the function will be −

const min = 3; const max = 9; const createRandom = (min, max) => { const diff = max - min; const random = Math.random(); return Math.floor((random * diff) + min); } console.log(createRandom(min, max));

Understanding the code −

- We take the difference of max and min
- We create a random number
- Then we multiply the diff and random to produce random number between 0 and diff
- Then we add min to it to produce the random number between min and max

Output for this code in the console will be −

6

Advertisements