Introduction
These days OTP is commonly used in applications running over the internet, OTP is commonly known as ONE TIME PASSWORD which is temporary, secure, and valid for one session or just for a few seconds that is sent to you via email or SMS to verify your authentication.
function generateotp() {
var digits = '1234567890';
var otp = ''
for (i = 0; i < 6; i++) {
otp += digits[Math.floor(Math.random() * 10)];
}
return otp;
}
When we call this function, each time we get six digit random OTP as you can see in the below image -

Now let us see if we have to generate a 4-digit OTP then we need to change the loop variable length only.
function generateotp() {
var digits = '1234567890';
var otp = ''
for (i = 0; i < 4; i++) {
otp += digits[Math.floor(Math.random() * 10)];
}
return otp;
}

Conclusion
You see how it's easy to generate a 4-digit or 6-digit or any length OTP in Javascript, each time you get a random number and we can merge this code to send an SMS or an email.

Sergio Martín NietoPosted Oct 10, 2022, 8:47 PM
Https://kemilbeltre.medium.com/why-do-not-use-math-random-a6f8b0ad38dd
Sergio Martín NietoPosted Oct 10, 2022, 8:47 PM
Math.random is not cryptographically secure and therefore not safe for use in Password generation scenarios. I recommend you reading the following article