HTML & CSS Course
HTML & CSS
/
Intermediate

LocalStorage & SessionStorage

Definition

Web Storage API provides mechanisms by which browsers can store key/value pairs locally, much more intuitively than using cookies.

Explain Like I'm New

It's a tiny database right inside your web browser. LocalStorage saves data forever (until the user manually clears their history). SessionStorage saves data only until the user closes the specific browser tab.

Real World Example

Saving a user's 'Dark Mode' preference. You save `theme = dark` in LocalStorage. Next week when they visit your site again, the browser checks LocalStorage and instantly turns the screen black.

Common Use Cases

  • •Saving user preferences
  • •Shopping cart data for unauthenticated users
  • •Saving form progress

Interactive Example

Interview Questions

basic

  • What is the difference between LocalStorage and SessionStorage?

intermediate

  • Can Web Storage store JavaScript Objects?

Flash Cards

Question

Local vs Session?

Click to reveal answer
Answer

LocalStorage persists even after the browser is closed and reopened. SessionStorage is instantly deleted the moment the tab is closed.

Question

Store Objects?

Click to reveal answer
Answer

No. Web Storage can ONLY store Strings. If you want to store a complex object or array, you must convert it to a string using `JSON.stringify()` before saving, and `JSON.parse()` when reading it back.