Generate OTP In Javascript

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 -

Generate OTP In Javascript

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;
}

Generate OTP In Javascript

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.