Generating Random Numbers can be useful for multiple purposes. This tutorial provides a complete guide to generating random numbers in JavaScript.
Before we dive deep into the process, let’s see some of the common use cases for generating random numbers.
Why Do We Need a Random Number Generator?
Below are some of the most command use cases of Generating Random Numbers.
Verification Code
You have seen these use cases very often, whenever we signup for a newsletter, or on the websites they send us a code to verify our email or contact number, this code is generated randomly and sent to you as well as the server to validate that the entered email or number is correct.
CAPTCHA
CAPTCHA is made up of two-part, the randomly generated values and the text box to enter that values to verify that the user is not a robot. The values can be a Random String containing letters and numbers, but some websites such as Flipkart for providing simplicity to their users just use Random Numbers.
Generating Random Numbers for CAPTCHA might not be a good idea in 2023, because the bot is not capable of reading it and bypassing it easily, instead, you can use Google reCAPTCHA, which we have covered in another tutorial Google reCAPTCHA Node.js tutorial if you want to read.
Random Pickups
The developer uses Random Numbers to pick up some value from an array in random order, this is useful when creating a game where it is necessary to randomize the event to make it more fun.
We have also used Random Generated Numbers in another tutorial Random Password Generator in NodeJS to pick distinct values from a string and concatenate them to generate a Random Strong Password.
Object Id
In JavaScript, whenever it is required to have multiple objects in an object, it is recommended to attach an id with every single of them, this id can be generated randomly and assigned to the objects.
There can be more use cases, but these are mostly used, let’s now see how to generate random numbers.
Generate Random Numbers in JavaScript
JavaScript has methods like Math.random() and Math.floor() which makes it super easy to Generate Random Numbers according to preference.
Using Javascript Math.random()
Math.random() method is used to generate a random floating point value from 0 up to 1 (exclusive).
Math.random();
Example:
let randomNumber = Math.random();
console.log(randomNumber);
Output:
0.30098319130131945
Setting a Range
Some basic mathematical operations can be done to set a custom range for generated numbers.
Math.random() * (highest - lowest) + lowest;
Example:
const lowest = 1;
const highest = 6;
let randomNumber = Math.random() * (highest - lowest) + lowest;
console.log(randomNumber);
Output:
3.4273051549033244
The generated number is a floating point number between 1 to 6 (exclusive).
Converting into Integers
Generated floating point values can be converted into an integer by using the Math.floor() method which returns the larger integer less than or equal to the given value.
Math.floor(randomNumber);
Example:
const lowest = 1;
const highest = 6;
let randomNumber = Math.random() * (highest - lowest) + lowest;
randomNumber = Math.floor(randomNumber);
console.log(randomNumber);
Output:
3
Define a Function to Generate Random Numbers
From the above concept, we can create a function that takes two arguments, the highest and lowest to generate a random number between them and returns it.
Below is the code to define a function to return a random number from a given range:
function generateRandomNumber(lowest, highest) {
let randomNumber = Math.random() * (highest - lowest) + lowest;
randomNumber = Math.floor(randomNumber);
return randomNumber;
}
These functions can be called whenever there is a requirement of generating a random number, it is better to create a function instead of repeating the whole processor, again and again, to generate random numbers in different blocks.
Calling the above function:
const randomNumber = generateRandomNumber(1, 1000);
console.log(randomNumber);
Output:
345
Summary
Generating the Random Number is useful in many scenarios, such as email verification, CAPTCHA, random pickup, etc. For this Math.random() method can be used, but it returns a randomly generated number in a floating point value, to convert it into an integer we can use the Math.floor() method. Hope this tutorial helps you to generate random numbers in JavaScript.
Reference
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor