loading...
Cover image for Vanilla JavaScript Random Number

Vanilla JavaScript Random Number

dailydevtips1 profile image Daily Dev Tips Originally published at daily-dev-tips.com ・2 min read

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);

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());

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

Posted on Jun 1 by:

dailydevtips1 profile

Daily Dev Tips

@dailydevtips1

I write daily development tips to contribute to the development community!

Discussion

markdown guide