How to Generate a Random Number between Two Numbers in JavaScript
Randomness is extremely useful in programming.
It allows you to simulate random events in your program and add unpredictability to your code.
In this post, we'll learn how you can generate a random number between two numbers in JavaScript.
How to generate a random number between two numbers in JavaScript
To start off, let's start with the low and high end of the range.
JAVASCRIPTconst low = 1;
const high = 10;
We can use this in conjunction with the Math.random()
function.
This function will return a random number between 0 and 1.
With some simple math, we can generate a random number between the low and high end.
JAVASCRIPTconst low = 1;
const high = 10;
const randomNumber = Math.floor(Math.random() * (high - low + 1)) + low;
console.log(randomNumber);
We use the Math.floor
function to round the random number down to the nearest integer.
You can also turn this into a function:
JAVASCRIPTconst low = 1;
const high = 10;
const getRandomNumber = (low, high) => {
return Math.floor(Math.random() * (high - low + 1)) + low;
}
console.log(getRandomNumber(low, high));
Keep in mind that this will include both the low and high numbers that you specified.
Conclusion
In this post, we learned how to generate a random number between two numbers in JavaScript.
With the function we have above, you can pass in a low and high end of the range and get a number within it.
Thanks for reading and happy coding!
- Getting Started with TypeScript
- How to Install Node on Windows, macOS and Linux
- How to Set Up Cron Jobs in Linux
- How to build a Discord bot using TypeScript
- How to deploy a Deno app using Docker
- Getting Started with Deno
- How to deploy a MySQL Server using Docker
- Learn how to use v-model with a custom Vue component
- Using Puppeteer and Jest for End-to-End Testing
- Getting Started with Moment.js
- Using Push.js to Display Web Browser Notifications
- Setting Up Stylus CSS Preprocessor