QJavaScript · Interview preparation
When should you use localStorage?
localStorage persists small string-based preferences across browser sessions.
The idea to remember.
localStorage persists small string-based preferences across browser sessions. Do not store sensitive authentication secrets there, and validate parsed values before using them.
01Learn by doing
From first example to real project.
Start with the smallest working idea, examine a more detailed example, then look at a real application pattern. Adapt dependencies, error handling and data models to your project.
Basic: delegate one listener
01 / BEGINNERA parent can handle events from matching children.
document.querySelector('#list').addEventListener('click', event => {
const button = event.target.closest('button[data-id]');
if (button) console.log(button.dataset.id);
});Intermediate: respect request lifecycles
02 / INTERMEDIATEAbort a pending request when it is no longer needed.
const controller = new AbortController();
fetch('/api/items', { signal: controller.signal });
// When the user navigates away:
controller.abort();Real scenario: safe persisted preferences
03 / REAL SCENARIOValidate stored data instead of assuming it is trustworthy.
function readTheme() {
const stored = localStorage.getItem('theme');
return stored === 'dark' ? 'dark' : 'light';
}
function saveTheme(theme) {
if (theme === 'dark' || theme === 'light') localStorage.setItem('theme', theme);
}02Check your understanding
Try it in your own words.
Explain when should you use localStorage without looking at the code. Then modify the intermediate example, describe one trade-off and identify when the real-world pattern fits.
Keep learning here.
Explore more in-depth guides, exercises and related interview questions in this library.
Browse JavaScript study guides ↗