How To Generate Random Code Of Given Length In JavaScript


Dec 09 2023

In this article, we will create a code snippet to generate a random alphanumeric code of a given length, which can be used in JavaScript and Node.js. Let's dive into it.

Before creating the script, let's take a look at the built-in methods we will use in JavaScript for generating random numbers and strings.

  • **Math.floor **-> Rounds a number down and return it. 5.90 -> 5.00
  • Math.random -> Generates a random number between 0 and 1
  • ** charAt** -> Returns the character at a specified index

So, here's an example code snippet in JavaScript that generates a random code of a given length.

function generateRandomCode(length) {
  let result = "";
  
  // You can extend your characters set
  const characters =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  const charactersLength = characters.length;
  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }

  return result;
}

The function above creates an empty string result and a charactersLength variable that stores the length of the characters string.

Using a for loop, the function generates a random index between 0 and charactersLength - 1, and appends the character at that index to the result string. This process is repeated length number of times to generate a code of the desired length.

Finally, the function returns the generated code.

Conclusion

In this brief guide, we have shown you a code snippet in javascript or nodejs, generating a code of given length, which is very useful while building any application such as generating verification code.

Thank you for reading.