DEV Community

Cover image for Vanilla JavaScript Random Number
Chris Bongers
Chris Bongers

Posted on • Originally published at daily-dev-tips.com

Vanilla JavaScript Random Number

Let's dive into making random numbers with JavaScript today; this comes in handy more often than you would think.

Random number using Math.random

We can use the Math.random() method to generate a random number; this is returned as a float. Which means it's a number between zero and one.

var number = Math.random();
console.log(number);
Enter fullscreen mode Exit fullscreen mode

This will return something like this 0.1433017075000662.

Getting a Number bigger than zero

But what if we need a number bigger than zero? Well we can make our own function for that.

var randomFunction = function() {
  return Math.random() * 100;
};
console.log(randomFunction());
Enter fullscreen mode Exit fullscreen mode

You can adjust the 100 to increase the number.
The current setup will return something like 34.68974860200957.

Now you know how to leverage Math.random() feel free to play with this Codepen.

See the Pen Vanilla JavaScript Random Number by Chris Bongers (@rebelchris) on CodePen.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Top comments (0)