Subscribe

Vanilla JavaScript Random Number

✍️

Today we are retrieving a random number with JavaScript

1 Jun, 2020 · 1 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.

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

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next 📖

Removing all vowels with JavaScript

3 Dec, 2022 · 2 min read

Removing all vowels with JavaScript

10 games to learn JavaScript

2 Dec, 2022 · 3 min read

10 games to learn JavaScript

Join 2097 devs and subscribe to my newsletter