# javascript random 4 digit number

## JavaScript Random 4 Digit Number

If you need to generate a random 4-digit number using JavaScript, there are a few ways to achieve this.

### Using Math.random()

The Math.random() function in JavaScript generates a random decimal number between 0 and 1. To generate a random 4-digit number, we can multiply the result of this function by 10000 and then use the Math.floor() function to round down to the nearest integer.


let randomNumber = Math.floor(Math.random() * 10000);


This code will generate a random 4-digit number between 0 and 9999.

### Using Date.now()

Another way to generate a random 4-digit number is to use the Date.now() function, which returns the current date and time in milliseconds since January 1, 1970. We can then use this value to calculate a random number.


let randomNumber = parseInt(Date.now().toString().slice(-4));


This code will generate a random 4-digit number based on the current timestamp.

### Using a Custom Function

If you want more control over how the random number is generated, you can create your own function that takes in a minimum and maximum value and returns a random integer within that range.


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

let randomNumber = getRandomNumber(1000, 9999);


This code will generate a random 4-digit number between 1000 and 9999.