Generate a random number between two numbers in JavaScript

If you need to generate a random number between two numbers in JavaScript, then you are in the right place! Here you will learn javascript random number generation.

We can easily do this by using a combination of built-in `Math` functions.

Javascript Random Number from Math.random()

Let’s start by using `Math.random()` to generate a random number. Now we will take that and multiply it by `max - min + 1`.

Because of how the `Math.random()` function works, we will need to then add the minimum value to this.

Once we are done, we pass it through a `Math.floor()` to get an absolute integer value (not a float).

Code example for Javascript Random Numbers

We can wrap this all into a function as follows:

```.wp-block-code{border:0;padding:0}.wp-block-code>div{overflow:auto}.shcb-language{border:0;clip:rect(1px,1px,1px,1px);-webkit-clip-path:inset(50%);clip-path:inset(50%);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px;word-wrap:normal;word-break:normal}.hljs{box-sizing:border-box}.hljs.shcb-code-table{display:table;width:100%}.hljs.shcb-code-table>.shcb-loc{color:inherit;display:table-row;width:100%}.hljs.shcb-code-table .shcb-loc>span{display:table-cell}.wp-block-code code.hljs:not(.shcb-wrap-lines){white-space:pre}.wp-block-code code.hljs.shcb-wrap-lines{white-space:pre-wrap}.hljs.shcb-line-numbers{border-spacing:0;counter-reset:line}.hljs.shcb-line-numbers>.shcb-loc{counter-increment:line}.hljs.shcb-line-numbers .shcb-loc>span{padding-left:.75em}.hljs.shcb-line-numbers .shcb-loc::before{border-right:1px solid #ddd;content:counter(line);display:table-cell;padding:0 .75em;text-align:right;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;white-space:nowrap;width:1%}```var generateRandomNumberBetween = function(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
};```Code language: JavaScript (javascript)```

Subscribe
Notify of