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.
const 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 function for that.
const 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