- 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
Outputting a random number that falls in a certain range in JavaScript
We are required to write a JavaScript function that takes in a number, say n, and an array of two numbers that represents a range. The function should return an array of n random elements all lying between the range provided by the second argument.
Therefore, let’s write the code for this function −
Example
The code for this will be −
const num = 10; const range = [5, 15]; const randomBetween = (a, b) => { return ((Math.random() * (b - a)) + a).toFixed(2); }; const randomBetweenRange = (num, range) => { const res = []; for(let i = 0; i < num; ){ const random = randomBetween(range[0], range[1]); if(!res.includes(random)){ res.push(random); i++; }; }; return res; }; console.log(randomBetweenRange(num, range));
Output
The output in the console will be −
[ '13.25', '10.31', '11.83', '5.25', '6.28', '9.99', '6.09', '7.58', '12.64', '8.92' ]
This is just one of the many possible outputs.
Advertisements