Algorithm


  1. 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.
  2. Use the Math.random() method:

    • Math.random() generates a random floating-point number between 0 (inclusive) and 1 (exclusive).
  3. 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.
  4. Ensure the result is an integer if needed:

    • If you need an integer rather than a floating-point number, use Math.floor(), Math.ceil(), or Math.round().
  5. 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

x
+
cmd
0.5856407221615856

#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

x
+
cmd
Random value between 1 and 10 is 7.392579122270686

#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

x
+
cmd
Random value between 1 and 10 is 2

#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

x
+
cmd
Enter a min value: 1
Enter a max value: 50
Random value between 1 and 50 is 47
Advertisements

Demonstration


Javascript Programing Example to Generate a Random Number-DevsEnv

Previous
JavaScript Practice Example #3 - Assign 3 Variables and Print Good Way