Skip to the solution
EasyFrontendAsked in 20246 min read

LocalStorage wrapper items TTL

2.7k views

The problem

Problem, as an interviewer would state it: "Wrap localStorage so each stored item has a TTL (time to live). Reading an expired item should return null and actually clean it up, not just report it as missing while leaving stale data sitting in storage forever."

Examples:

Code
setWithTTL("session", "abc123", 100); // expires in 100ms
getWithTTL("session"); // "abc123" (still valid)
// after 150ms...
getWithTTL("session"); // null, AND the raw entry is genuinely removed from storage

Clarifying questions expected:

  • Should expired entries be cleaned up lazily (only when read) or proactively (a background sweep)?
  • What should happen if a stored value isn't valid JSON (corrupted or from an older, incompatible format)?
  • Is a global default TTL needed, or is TTL always specified per item?

Code / implementation expected: Yes — real, live-verified proof: a value reads correctly before expiry, reads as null after expiry, and the underlying raw localStorage entry is genuinely removed as a side effect of that expired read.

  • js-coding
  • utility
  • algorithm

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, live-verified proof: a localStorage TTL wrapper correctly reads before expiry, returns null after, and genuinely self-cleans the raw entry — verified directly

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 7 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextEasy

Wrap methods hook decorator

Continue