Explain Codes LogoExplain Codes Logo

Random alpha-numeric string in JavaScript?

javascript
randomness
string-generation
math.random
Alex KataevbyAlex KataevΒ·Jan 4, 2025
⚑TLDR

Here's a fast and reliable way to get a random alpha-numeric string:

function fastRandString(n) { // Array(n) creates an empty array of length 'n'. // Array.map() fills it with random alphanumeric characters. // Not just 'fast'. It's 'to-the-moon' fast! πŸš€ return [...Array(n)].map(() => (~~(Math.random() * 36)).toString(36)).join(''); } // Like ordering a 10-char string with extra randomness! πŸ”πŸŒΆ console.log(fastRandString(10));

Inner workings

Let's break down the code for a better understanding:

Mathematics meets randomness

The Math.random() function is our random number generator. It produces a floating-point number between 0 (inclusive) and 1 (exclusive). By chaining toString(36), we are converting this number to a base-36 representation (0-9 and a-z). The slice(2) function is our castle guard, fending off the "0." from the result! 🏰

String length and collisions

The randomness nature of Math.random() eventually leads to duplicates. The estimated boundary before a duplicate occurs is approximately 70 million strings (nearly the population of the UK! πŸ‡¬πŸ‡§).

Feeling fancy? Use (Math.random()*1e32).toString(36) and .substr to control the size of your strings!

Crafting better randomness

If your project demands higher reliability, you may need some extra tools:

Reaching for libraries

Libraries like lodash provide _.random which offers a uniform distribution and a higher degree of unpredictability, kind of like rolling a dice you can't see! 🎲

Uniqueness and collisions

Forming truly unique strings is a challenging task. It's like having twins! πŸ‘―β€β™‚οΈ Look for external libraries, such as uuid, for better reliability.

Uppercase letters inclusion

Our base-36 conversion turned out to be slightly discriminatory. It's not including uppercase letters! To fix this, simply mix in uppercase letters to your character set:

function randomAlphaNumeric(length) { const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; return [...Array(length)].map(() => chars.charAt(Math.floor(Math.random() * chars.length))).join(''); }

Takeaways: Variety is the spice of code

When choosing the right method for random string generation, consider the context:

  • Lightweight web applications? Base-36 conversion all the way!
  • Batch processing? Opt for libraries or efficient string concatenation.
  • Security-intensive? Rely on the Crypto API for a cryptographically strong randomness.