Exercise 8: Generate Random String (alphanumeric)

Problem Statement

Create a function `randomString(length=8)` that generates a random alphanumeric string. Example: randomString(6) → "a3B9x2"

Sample Output:

randomString(6) => "a3B9x2" (random)
randomString(10) => "Xy7mN2pQ9k" (random)
randomString(4) => "K9mP" (random)

Solution

const randomString = (length = 8) => {
  const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  return Array.from({ length }, () => chars[Math.floor(Math.random() * chars.length)]).join("");
};

Explanation

Overall Goal:

  • Random alphanumeric string generate karna (A-Z, a-z, 0-9).
  • Specified length ka string return karna.

Line 1: Function header

  • const randomString = (length = 8) => {
  • Default length 8 characters.

Line 2: Character set

  • const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  • All possible characters jo string me use honge.

Line 3: Generate string

  • Array.from({ length }, ...)length size ka array banata hai.
  • () => chars[Math.floor(Math.random() * chars.length)] → har position pe random character:
  • Math.random() → 0-1 ke beech random number.
  • * chars.length → 0-61 ke beech number.
  • Math.floor(...) → integer me convert.
  • chars[index] → random character pick.
  • .join("") → array ko string me convert.

Real world:

  • Password generation: temporary passwords.
  • Token generation: API keys, session tokens.
  • Unique IDs: short URLs, referral codes.