Generate Random numbers in Javascript

In this Javascript program we will cover how to generate random numbers. We all know to generate random numbers we will use Math package with Math.random() method.

Let's write program

<script>
const x = Math.random();
console.log(x);
</script>

 

 

Generally Math.random() generate random numbers with given range, normally 0 to 1. So this will generate below output without given range.

Output:

0.39122962255698623

 

 

Generate Random Numbers with Given range

Syntax:

Math.random() * (highestNumber - lowestNumber) + lowestNumber

 

Write example to generate random numbers with in given range

<script>

// a program for random number between 15 and 100
const a=15;
const b=100;
const x = Math.random() * (b-a) + a
console.log(`Random number between ${a} and ${b} = ${x}`);
</script>

 

Output

Random number between 15 and 100 = 33.30355790059883

 

Generate Random Integers or whole numbers in Javascript

Always Math.random() generate decimal numbers, to generate integer or whole numbers we can use Math.floor() method.

Syntax:

Math.floor(Math.random() * (highestNumber - lowestNumber)) + lowestNumber

 

Example

<script>

// a program for random number Integer between 15 and 100
const a=15;
const b=100;
const x = Math.floor(Math.random() * (b-a)) + a; 
console.log(`Random number between ${a} and ${b} = ${x}`);
</script>

 

 

Output:

Random number between 15 and 100 = 16

 

Subscribe For Daily Updates

100+ Python Pattern Examplespython pattern examples - star patterns, number patterns