JavaScript Storage
Modern web applications need to remember user state: dark mode preferences, items in a shopping cart, or login tokens. The Web Storage API provides mechanisms to store this data right in the browser.
localStorage
localStorage persists data indefinitely across browser sessions. Data stored here will not be deleted when the browser is closed. It is domain-specific, meaning your site cannot read the localStorage of another site.
localStorage.setItem('key', 'value'): Saves data.localStorage.getItem('key'): Retrieves data. Returnsnullif it doesn't exist.localStorage.removeItem('key'): Deletes a specific key.
sessionStorage
sessionStorage maintains a separate storage area for each given origin that's available for the duration of the page session (as long as the browser tab is open). If you open multiple tabs of the same site, they will have different sessionStorage instances.
The JSON Trap
A critical limitation of the Web Storage API is that keys and values are always strings. If you try to pass an object like { user: "Alice" } to setItem, it gets converted to the useless string "[object Object]".
To store complex data structures, you must serialize them using JSON.stringify() before saving, and deserialize them using JSON.parse() upon retrieval.
What about Cookies?+
Before Web Storage, we used Cookies. Cookies are small pieces of data (up to 4KB) that are stored by the browser and automatically sent back to the server with every HTTP request.
While they are essential for server-side session management (like authentication tokens), they are generally avoided for pure client-side storage today because they slow down network requests and have a clunky API (`document.cookie`). Use `localStorage` or `sessionStorage` whenever the data only needs to be accessed by the frontend.
