How to generate random numbers in JavaScript

In JavaScript, you can use the Math. random() function to generate a pseudo-random floating number between 0 (inclusive) and 1 (exclusive).

const random = Math.random()

console.log(random)
// 0.5362036769798451

If you want to get a random number between 0 and 20, just multiply the results of Math.random() by 20:

const random = Math.random() * 20

console.log(random)
// 15.40476356200032

To generate a random whole number, you can use the following Math methods along with Math.random():

  • Math.ceil() — Rounds a number upwards to the nearest integer
  • Math.floor() — Rounds a number downwards to the nearest integer
  • Math.round() — Rounds a number to the nearest integer

Let us use Math.floor() to round the floating number generated by Math.random() to a whole number:

const random = Math.floor(Math.random() * 20)

console.log(random)
// 12

Now we have learned that how to generate a whole random number, let us write a function that takes in an integer as input and returns a whole number between 0 and the integer itself:

const random = (max = 50) => {
    return Math.floor(Math.random() * max)
}

console.log(random(100))
// 66

To generate a random number between two specific numbers (min included, max excluded), we have to update the random() method like below:

const random = (min = 0, max = 50) => {
    let num = Math.random() * (max - min) + min

    return Math.floor(num)
}

console.log(random(10, 40))
// 28

In the above code, we used (max - min) + min to avoid cases where the max number is less than the min number.

To generate a random number that includes both min and max values, just change Math.floor() to Math.round():

const random = (min = 0, max = 50) => {
    let num = Math.random() * (max - min) + min

    return Math.round(num)
}

console.log(random(10, 70))
// 51

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.