Algorithm
-
Define a function for generating a random number:
- Name the function, e.g.,
generateRandomNumber
. - This function may take parameters for specifying a range if needed.
- Name the function, e.g.,
-
Use the
Math.random()
method:Math.random()
generates a random floating-point number between 0 (inclusive) and 1 (exclusive).
-
Adjust the range if necessary:
- If you want a random number within a specific range (e.g., between 1 and 100), you can multiply the result of
Math.random()
and add the minimum value.
- If you want a random number within a specific range (e.g., between 1 and 100), you can multiply the result of
-
Ensure the result is an integer if needed:
- If you need an integer rather than a floating-point number, use
Math.floor()
,Math.ceil()
, orMath.round()
.
- If you need an integer rather than a floating-point number, use
-
Return the random number:
- Make sure the function returns the generated random number.
Code Examples
#1 Code Example- Generate a Random Number
Code -
Javascript Programming
// generating a random number
const a = Math.random();
console.log(a);
Copy The Code &
Try With Live Editor
Output
#2 Code Example- Get a Random Number between 1 and 10
Code -
Javascript Programming
// generating a random number
const a = Math.random() * (10-1) + 1
console.log(`Random value between 1 and 10 is ${a}`);
Copy The Code &
Try With Live Editor
Output
#3 Code Example- Integer Value between 1 and 10
Code -
Javascript Programming
// generating a random number
const a = Math.floor(Math.random() * (10 - 1)) + 1;
console.log(`Random value between 1 and 10 is ${a}`);
Copy The Code &
Try With Live Editor
Output
#4 Code Example- Integer Value between Two Numbers (Inclusive)
Code -
Javascript Programming
// input from the user
const min = parseInt(prompt("Enter a min value: "));
const max = parseInt(prompt("Enter a max value: "));
// generating a random number
const a = Math.floor(Math.random() * (max - min + 1)) + min;
// display a random number
console.log(`Random value between ${min} and ${max} is ${a}`);
Copy The Code &
Try With Live Editor
Output
Enter a max value: 50
Random value between 1 and 50 is 47
Demonstration
Javascript Programing Example to Generate a Random Number-DevsEnv