Categories
JavaScript Answers

How to Generate a 4 Digit Random Number with JavaScript?

Spread the love

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.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published. Required fields are marked *