Categories

# How to Generate a 4 Digit Random Number with JavaScript?

Sometimes, we want to generate a 4 digit random number with JavaScript.

In this article, we’ll look at how to generate a 4 digit random number with JavaScript.

### Generate a 4 Digit Random Number with JavaScript

To generate a 4 digit random number with JavaScript, we can use the `Math.random` method.

For instance, we can write:

``````const val = Math.floor(1000 + Math.random() * 9000);
console.log(val);
``````

We call the `Math.random` method to generate a random number between 0 and 1.

Then we multiply that by 9000 to get a number between 0 and 9000.

Then to get a number between 0 and 10000, we add 1000 to the returned number.

Finally, we call `Math.floor` on the generated number to round it down to a number between 1000 and 9999.

### Conclusion

To generate a 4 digit random number with JavaScript, we can use the `Math.random` method. ## By John Au-Yeung

Web developer specializing in React, Vue, and front end development.