What is localStorage and sessionStorage?

Answer

Both are Web Storage APIs for storing key-value pairs in the browser as strings, but they differ in persistence. localStorage persists data with no expiration — it survives browser restarts and lasts until explicitly cleared by JavaScript or the user. sessionStorage persists data only for the current browser tab/session — data is cleared when the tab is closed. Both have the same API: localStorage.setItem("key", "value"), localStorage.getItem("key"), localStorage.removeItem("key"), localStorage.clear(), localStorage.length. Only strings are stored — serialize objects with JSON.stringify() and parse with JSON.parse(). Storage limit is typically 5-10 MB. Both are synchronous (can block the main thread for large data) and accessible only to same-origin pages. Never store sensitive data (passwords, tokens) in Web Storage — it is accessible to JavaScript and vulnerable to XSS attacks. Use secure, HttpOnly cookies for auth tokens.