Exercise 5: Clear Keys by Prefix

Problem Statement

Create a function `clearByPrefix(prefix)` that deletes matching keys from localStorage.

Sample Output:

clearByPrefix("user_")
// Deletes: user_name, user_email, user_id (if exist)
clearByPrefix("cache_")
// Deletes: cache_posts, cache_users (if exist)

Solution

const clearByPrefix = (prefix) => {
  const keys = Object.keys(localStorage).filter((k) => k.startsWith(prefix));
  keys.forEach((k) => localStorage.removeItem(k));
};

Explanation

Overall Goal:

  • localStorage se specific prefix wale sabhi keys delete karna.
  • Bulk cleanup: related keys ek saath remove.

Line 1: Function header

  • const clearByPrefix = (prefix) => {
  • prefix → string prefix (e.g., "user_", "cache_").

Line 2: Get matching keys

  • const keys = Object.keys(localStorage).filter((k) => k.startsWith(prefix));
  • Object.keys(localStorage) → localStorage ke sabhi keys ka array.
  • .filter((k) => k.startsWith(prefix))
  • startsWith(prefix) → kya key prefix se start hoti hai?
  • Sirf matching keys filter ho jayengi.
  • Example: prefix "user_"["user_name", "user_email"] filter.

Line 3: Delete keys

  • keys.forEach((k) => localStorage.removeItem(k));
  • forEach → har key ke liye loop.
  • removeItem(k) → key-value pair delete karta hai.

Example:

  • clearByPrefix("user_")user_name, user_email delete.
  • clearByPrefix("cache_")cache_posts, cache_users delete.

Real world:

  • Logout: user-related data cleanup.
  • Cache invalidation: old cache keys remove.
  • Namespace cleanup: related data ek saath delete.