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.