Table of Contents

In this post, we will see how to generate random number between 1 to 10 in javascript.

## How to generate random number between 1 and 10 in javascript

We can simply Math.random() method to generate random number between 1 and 10 in javascript.

`Math.random()`

returns a random number between 0(inclusive), and 1(exclusive). That means `Math.random()`

returns always number lower than 1.

We can use `Math.random()`

with `Math.floor()`

to generate random integer.

Here is generic formula to generate random number in the range.

**Math.floor(Math.random() * (maximum – minimum + 1)) + minimum**

In our case,

minimum = 1

maximum = 10

so it will be

**Math.floor(Math.random() * (10 – 1 + 1)) + 1**

**Math.floor(Math.random() * 10) + 1**

So here is the program to generate random number between 1 and 10 in javascript.

1 2 3 4 |
var randNum = Math.floor(Math.random() * 10) + 1; console.log(randNum) |

When you run above program, you will get below output:

You can get different outputs as we are generating random numbers here.

## Generate 10 random integers in range of 1 to 10

We can simply use for loop to iterate over the above code to generate 10 random numbers.

1 2 3 4 5 6 7 |
console.log("Generating 10 random integers in range of 1 to 10") for (let i = 0; i < 10; i++) { var randNum = Math.floor(Math.random() * 10) + 1; console.log(randNum) } |

7

5

1

10

5

9

7

7

6

2

## Further reading:

## Generate random number in a range in javascript

Here is generic formula to generate random number in a range.

1 2 3 4 5 6 7 8 9 10 11 12 |
function generateRandomInteger(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } // Generate random number between 1 to 10 console.log(generateRandomInteger(1,10)) // Generate random number between 11 to 20 console.log(generateRandomInteger(11,20)) // Generate random number between 21 to 30 console.log(generateRandomInteger(21,30)) |

17

28

In case you don’t want to include maximum while generating random numbers, you can use the below function.

1 2 3 4 5 |
function generateRandomInteger(min, max) { return Math.floor(Math.random() * (max - min)) + min; } |

That’s all about how to generate random number between 1 and 10 in javascript.