How to generate one-time password (OTP) in JavaScript

in any web application, a One-Time Password (OTP) is a password that is valid for only one login session or transaction. It is commonly used for different purposes like Internet Banking, online transactions, log-in or registration forms, and many more. OTPs are typically a combination of 4 or 6 numeric digits or a 6-digit alphanumeric code.

For generating an OTP in JavaScript, we can use Math.random() function with the combination of Math.floor(). Math.random() function returns a random floating-point number between 0 (inclusive) and 1 (exclusive). To convert this random number into an OTP, we can multiply it by the number of possible characters and use the result as an index to pick characters from a predefined set.

Used Function:

  • Math.random(): This function returns any random number between 0 (inclusive) and 1 (exclusive).
  • Math.floor(): It returns the floor (down) of any floating number to an integer value.


Using the above function we can pick a random index of a string array that contains all the possible conditions of a particular digit of the OTP.

Here is an example to generate OTP in js:

        
        function generateOtp(limit) {
  // Ensure that the limit is a positive integer
  if (typeof limit !== 'number' || limit <= 0 || !Number.isInteger(limit)) {
    throw new Error('Limit must be a positive integer');
  }

  // Define characters that can be used in the OTP
  const characters = '0123456789';

  // Initialize the OTP variable
  let otp = '';

  // Generate the OTP by randomly selecting characters from the defined set
  for (let i = 0; i < limit; i++) {
    const randomIndex = Math.floor(Math.random() * characters.length);
    otp += characters.charAt(randomIndex);
  }

  return otp;
}

// Example usage: generate a 6-digit OTP
const otp = generateOtp(6);
console.log(otp);

// Example usage: generate a 4-digit OTP
const otp2= generateOtp(4);
console.log(otp2);
        
    

Leave a comment