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 own 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 ๐Ÿ“–

TypeORM viewEntity

30 Mar, 2022 ยท 5 min read

TypeORM viewEntity

The Record Utility Type in TypeScript

12 Mar, 2022 ยท 3 min read

The Record Utility Type in TypeScript

Join 1372 devs and subscribe to my newsletter