DEV Community

MrSrv7
MrSrv7

Posted on

Generate a Non Repetitive One Time Password (OTP) in Vanilla JS

  Have you wondered how to write a simple JavaScript (Vanilla JS) function to generate text or numbers? In this case, a JavaScript function that generates a nonrepetitive OTP. There might be libraries and frameworks for your backend services to make use of, for the functionality of verifying the users or similar. Yet, you can be asked in an interview to write a code for the same, or your project's bundle size might be a critical factor, so you might not be able to include a separate package just for generating text or numbers. So, let's discuss how to achieve the same via Vanilla JS.

Code

const generateOtp = (otpLength = 6) => {
  let otpCode = "";
  const possibleDigits = "0123456789";
  while (otpCode.length < otpLength) {
    let currentDigit = possibleDigits.charAt(
      Math.floor(Math.random() * possibleDigits.length)
    );
    if (!otpCode.includes(currentDigit)) {
      otpCode += currentDigit;
    }
  }
  return otpCode;
};

console.log(`Your OTP is ${generateOtp()}`); // As the function is called without any parameters, the default value of 6 will be considered as the length of the OTP

console.log(`Your OTP is ${generateOtp(4)}`); // For four digit OTP
Enter fullscreen mode Exit fullscreen mode

Preview in CodeSandBox

Explanation

  • First, create a function named generateOTP and pass in a required parameter otpLength.
  • A default value of 6 is assigned for OTP length if no parameter is passed.
  • Declare a variable otpCode that will be returned when the function is called.
  • Declare a variable possibleDigits that holds the digits/characters to be considered for generating the OTP.
  • The while loop is executed until otpCode.length is less than otpLength. That is, the loop will execute till it generates the otpLength of numbers (in this case, its six digits)
  • Within the loop, generate a random character from the possibleDigits string using possibleDigits.charAt(Math.floor(Math.random() * possibleDigits.length)) and store the index in a temporary variable currentDigit
  • Check if the generated character exists in otpCode using if (!otpCode.includes(currentDigit)).
  • If it doesn't exist, add the generated character to the otpCode string using otpCode += currentDigit.
  • The function returns the generated OTP using the return otpCode statement.;

Output

 You can make use of such functions and make multiple generators for your use case, especially with the help of regex (regular expressions) to have ultimate customized generator functions without any 3rd party library. This approach helps you to understand the underlying concept and will help you to come up with similar solutions to similar questions in interviews, coding rounds, etc. when attending interviews.

  Do suggest me for any such topics to cover in future. Do let me know in the comments if this helped you at any situation.

Top comments (2)

Collapse
 
jagdishlove profile image
Jagdish Singh Mehra

Amazing dude, clean explanation.

Collapse
 
mrsrv7 profile image
MrSrv7

Thanks @jagdishlove :)