AppDividend
Latest Code Tutorials

# Javascript Math Random Tutorial | Math.random() Example

Javascript Math Random Tutorial | Math.random() Example is today’s topic.  It returns a random number between 0 (inclusive) and 1 (exclusive). The implementation selects the initial seed to a random number generation algorithm; it cannot be chosen or reset by the user.

## Javascript Math Random Tutorial

The syntax of Math.random() function is following.

`Math.random()`

It returns the floating-point, a pseudo-random number between 0 (inclusive) and 1 (exclusive).

Let’s see the example.

```// app.js

console.log(Math.random());```

The output is following.

The Math.random() does not provide the cryptographically secure random numbers. Do not use them for anything related to security.

## Getting a random number between two values

The Math.random() method explicitly does not provide the arguments that can return the values between two numbers. Although we can create a method that can do for you. See the following example.

```// app.js

const app = (min, max) => {
return Math.random() * (max - min) + min;
}

console.log(app(19, 25));```

The output is following.

All the random values will be generated between those two arguments. In the above example, all the values are generated in floating values. You can also generate the integer values as well. See the following example.

```// app.js

const app = (min, max) => {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}

console.log(app(19, 25));```

The output is following.

So, we have seen how we can use the Math.random() function to generate the random values in float as well as an integer.

Finally, Javascript Math Random Tutorial | Math.random() Example is over.

This site uses Akismet to reduce spam. Learn how your comment data is processed.