Intermediate JavaScript Interview QuestionsIntermediateComparison
JavaScript · Question 56
What is the difference between cookies, localStorage, and sessionStorage?
Direct answer
Cookies are HTTP state that can be sent with matching requests and can use security attributes; localStorage and sessionStorage are synchronous origin-scoped browser storage APIs for string data, with different lifetimes and tab/session behavior.
- Cookies — small HTTP-oriented state; matching cookies may be attached to requests. Attributes such as
HttpOnly,Secure, andSameSitematerially affect security and delivery. - localStorage — persists for the origin until cleared/evicted according to browser behavior; JavaScript reads/writes string keys synchronously.
- sessionStorage — scoped to an origin within a particular top-level browsing context/session and normally cleared when that page session ends.
Because Web Storage is synchronous, large or frequent serialization can block the main thread. For larger structured client-side data, IndexedDB is usually a more appropriate browser storage mechanism.
Security is not simply “cookies bad, localStorage good” or the reverse. XSS can read script-accessible storage, while HttpOnly cookies prevent JavaScript access but require CSRF/session design considerations.