How To Generate A Random Number In Javascript

How To Generate A Random Number In Javascript

·

1 min read

In this post, we will be covering how to generate a random number with JavaScript.

Math.random()

You can use Math.random() to generate a random number between 0 and 1.

Syntax Math.random();

The number you end up generating is long with many decimal places. Therefore, in practice, you need to do some manipulation to this random number before it has any practical use.

Generating a random integer

For the most part, we want to generate random integers.

To do this, we need to do two things.

We need to multiply the randomly generated number by an integer, and then we need to round that integer either up or down.

JavaScript Code

Math.floor(Math.random() * 2);

The above example generates a random number between 0 and 1.

How To Create A Random Integer Function

The following example is a function that returns a random integer between a maximum and a minimum value (both inclusively).

JavaScript Code

function getRndInteger(min, max) 
{ return Math.floor(Math.random() * (max – min + 1) ) + min; }

You can also exclude the max value by removing the +1.

JavaScript Code

function getRndInteger(min, max)
{ return Math.floor(Math.random() * (max – min) ) + min; }