- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to create a random number between a range JavaScript
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 −
Example
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
Output for this code in the console will be −
6
Advertisements