How to Generate 6 Digit Random Number Typescript?

Hello Friends Today, through this tutorial, I will tell you how to generate a 6 digit Unique random number in TypeScript.

While generating a truly unique random number across all users and sessions is impossible in JavaScript due to its client-side nature, you can achieve a ‘high degree of uniqueness’ by combining multiple techniques:

Using `Math.random()` and Date.now()`.

function generateUniqueSixDigitNumber(): number {
// Combine current timestamp with random number for better uniqueness
const baseNumber = Math.floor(Math.random() * 1000000) + Date.now();

// Ensure the number has 6 digits by adding or removing the thousands digit
const numberString = baseNumber.toString();
if (numberString.length < 6) {
return parseInt(numberString.padStart(6, '0'));
} else if (numberString.length > 6) {
return parseInt(numberString.slice(0, 6));
}

// If a duplicate still occurs (unlikely), generate another one recursively
return generateUniqueSixDigitNumber();
}

const uniqueNumber = generateUniqueSixDigitNumber();
console.log("Generated unique 6-digit number:", uniqueNumber);

Explanation-

1. The function first combines the current timestamp (`Date.now()`) with a random number (`Math.random()` multiplied by 1 million and floored) to increase uniqueness.
2. It checks the length of the resulting number as a string.
3. If the number is less than 6 digits, it prepads it with zeros using `padStart(6, ‘0’)`.
4. If the number is more than 6 digits, it slices the string to keep only the first 6 digits.
5. As an extra layer of precaution, the function uses recursion to generate another number if the current one might be a duplicate (highly unlikely).