JavaScript: Generate a random integer
JavaScript Math: Exercise-4 with Solution
Generate a Random Integer
Write a JavaScript function to generate a random integer.
Test Data :
console.log(rand(20,1));
console.log(rand(1,10));
console.log(rand(6));
console.log(rand());
15
5
1
0
Visual Presentation:
Sample Solution:
JavaScript Code:
Output:
4 1 2 0
Explanation:
In the exercise above,
- The code defines a function called "rand()" which generates a random integer within a specified range.
- The "rand()" function takes two parameters: 'min' and 'max', representing the minimum and maximum values of the range.
- Inside the function:
- If both 'min' and 'max' parameters are not provided (null), it returns 0.
- If only one parameter is provided (which is treated as the maximum value), it sets the minimum value to 0.
- It then generates a random integer between 'min' (inclusive) and 'max' (inclusive) using "Math.random()" and some arithmetic operations.
Flowchart:

Live Demo:
For more Practice: Solve these Related Problems:
- Write a JavaScript function that generates a random integer within a specified range and ensures uniform distribution.
- Write a JavaScript function that generates a random integer using Math.random() and rounds the result using bitwise operators.
- Write a JavaScript function that accepts optional minimum and maximum parameters to generate a random integer, using default values when omitted.
- Write a JavaScript function that repeatedly generates random integers until a prime number is produced.
Improve this sample solution and post your code through Disqus.
Previous: Write a JavaScript function to convert a decimal number to binary, hexadecimal or octal number.
Next: Write a JavaScript function to format a number up to specified decimal places.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.