EasyBrowser APIs📖 Theory Question

What is the difference between localStorage, sessionStorage, and cookies?

💡

Hint

Differ in persistence, scope, size, and whether auto-sent to server

Full Answer

FeaturelocalStoragesessionStorageCookie
LifetimePersistent (until cleared)Tab session onlyExpiry date / session
ScopeSame origin, all tabsSame tab onlyDomain + path
Size limit~5-10 MB~5-10 MB~4 KB
Sent to serverNoNoYes (every request)
JS accessYesYesYes (unless HttpOnly)
// localStorage / sessionStorage — same API
localStorage.setItem('theme', 'dark');
localStorage.getItem('theme');    // 'dark'
localStorage.removeItem('theme');
localStorage.clear();

// Must stringify objects
localStorage.setItem('user', JSON.stringify({ name: 'Alice', id: 1 }));
const user = JSON.parse(localStorage.getItem('user'));
💡 Never store auth tokens or sensitive data in localStorage/sessionStorage — XSS attacks can steal it. Use HttpOnly cookies for auth tokens — they're inaccessible to JavaScript.

More Browser APIs Questions

EasyWhat is the Fetch API and how do you handle errors correctly?→MediumWhat are Web Workers and when should you use them?→MediumWhat are Service Workers and what problems do they solve?→MediumWhat is the Same-Origin Policy and how does CORS work?→

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint