# Generate random number within a range in JavaScript

**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.**

TOP Interview Coding Problems/Challenges

- Run-length encoding (find/print frequency of letters in a string)
- Sort an array of 0's, 1's and 2's in linear time complexity
- Checking Anagrams (check whether two string is anagrams or not)
- Relative sorting algorithm
- Finding subarray with given sum
- Find the level in a binary tree with given sum K
- Check whether a Binary Tree is BST (Binary Search Tree) or not
- 1[0]1 Pattern Count
- Capitalize first and last letter of each word in a line
- Print vertical sum of a binary tree
- Print Boundary Sum of a Binary Tree
- Reverse a single linked list
- Greedy Strategy to solve major algorithm problems
- Job sequencing problem
- Root to leaf Path Sum
- Exit Point in a Matrix
- Find length of loop in a linked list
- Toppers of Class
- Print All Nodes that don't have Sibling
- Transform to Sum Tree
- Shortest Source to Destination Path

Comments and Discussions

**Ad:**
Are you a blogger? Join our Blogging forum.