**JavaScript code to generate random numbers within a range** - In this article, we will learn how we can generate a random number using Math.random() and some mathematical manipulation between a range?

Submitted by Abhishek Pathak, on October 02, 2017

JavaScript is a front-end scripting language. Many a times we need to **generate random numbers between a range**, say for an input. JavaScript has its own built in Math library and under that we have random function, which is like **'Math.random()'**, but it generates floating numbers between 0 and 1.

So, manipulating it with some other Math functions and simple maths logic, we can **generate random numbers between a range**. Here, is a simple program to do so.

**JavaScript code to generate random numbers within a range **

function randomNumber(start, end) { var diff = end - start; return Math.floor((Math.random)*diff + start); } console.log(randomNumber(1111, 9999));

**Explanation**

Looks unusual? It might look by just looking but it is not actually.

Only a simple logic is followed. First, we have taken the difference between starting range and end range.

As we know, **'Math.random()'** returns numbers between 0 and 1. So the minimum number it will return is 0. Now if a number is multiplied with 0 (diff here), it will be 0. Adding the starting range to 0 will give the starting number itself.

Now, the maximum number randomly generated will be 1. If this is multiplied with difference, it will result difference. Now adding this difference to starting range, will give out nothing but the end range. Simple maths, right? Likewise, the maths goes for all the floating numbers between 0 to 1.

**If you find this useful or a better way, leave down comments below.**

Are you a blogger? Join our Blogging forum.

Comments and Discussions

.resCodeAS1 { display: block; width: 320px; height: 50px; }
@media(min-width: 300px) { .resCodeAS1 { display: none; } }
@media(min-width: 480px) { .resCodeAS1 { display: none; } }
@media(min-width: 750px) { .resCodeAS1 { display: block; width: 336px; height: 280px; } }
(adsbygoogle = window.adsbygoogle || []).push({});

(adsbygoogle = window.adsbygoogle || []).push({});

(adsbygoogle = window.adsbygoogle || []).push({});

solved programs: » C » C++ » DS » Java » C# |

aptitude que. & ans.: » C » C++ » Java » DBMS |

interview que. & ans.: » C » Embedded C » Java » SEO » HR |

Like other websites, this site uses cookies to deliver relevant ads based on your interest, by using our website, you acknowledge that you have read our privacy policy.

Close