Exercise 1: Password Strength (basic)

Problem Statement

Create a function `passwordStrength(pw)` that returns "weak" | "medium" | "strong". Rules: - strong: length>=8 AND has uppercase AND has lowercase AND has digit - medium: length>=6 AND (has digit OR has uppercase) - else weak

Sample Output:

passwordStrength("Password123") => "strong"
passwordStrength("Pass1") => "medium"
passwordStrength("pass") => "weak"

Solution

const passwordStrength = (pw) => {
  const s = String(pw ?? '');
  const hasU = /[A-Z]/.test(s);
  const hasL = /[a-z]/.test(s);
  const hasD = /\d/.test(s);
  if (s.length >= 8 && hasU && hasL && hasD) return 'strong';
  if (s.length >= 6 && (hasD || hasU)) return 'medium';
  return 'weak';
};

Explanation

Overall Goal:

  • Password ki strength check karna: "weak", "medium", ya "strong".
  • Rules: length, uppercase, lowercase, digits check karna.

Line 1: Function header

  • const passwordStrength = (pw) => { → function jo password string lega.

Line 2: String normalization

  • const s = String(pw ?? '');
  • pw ?? '' → nullish coalescing: agar pw null/undefined hai to empty string use karo.
  • String(...) → guarantee karta hai ki result string hi hoga.

Line 3-5: Regex checks

  • const hasU = /[A-Z]/.test(s); → uppercase check:
  • /[A-Z]/ → regex pattern jo A se Z tak koi bhi uppercase letter dhundhta hai.
  • .test(s) → string me pattern match hota hai ya nahi (true/false).
  • const hasL = /[a-z]/.test(s); → lowercase check (a-z).
  • const hasD = /\\d/.test(s); → digit check:
  • \\d → regex me \d means any digit (0-9).

Line 6: Strong password check

  • if (s.length >= 8 && hasU && hasL && hasD) return 'strong';
  • && (AND operator) → sabhi conditions true honi chahiye:
  • Length >= 8 aur uppercase hai aur lowercase hai aur digit hai.
  • Early return: agar strong hai to turant return, aage check nahi karna.

Line 7: Medium password check

  • if (s.length >= 6 && (hasD || hasU)) return 'medium';
  • Length >= 6 aur (digit hai ya uppercase hai).
  • || (OR operator) → dono me se koi ek true ho to chalega.

Line 8: Default (weak)

  • return 'weak'; → agar upar ki dono conditions fail ho gayi to weak.

Real world:

  • Signup forms me password strength indicator dikhana.
  • User ko feedback dena ki password kitna strong hai.

Navigation

Previous

No previous exercise

Next

Exercise 2

View All Categories