JavaScript Interview Question #134

What is the difference between localStorage and sessionStorage?

Generators, Browser Storage, Security & Advanced Runtime Concepts Senior Advanced

Quick Interview Answer

Both APIs provide origin-scoped string key-value storage with a similar interface. localStorage generally persists until the data is explicitly removed, while sessionStorage is scoped to a particular browser tab or page session and is cleared when that session ends.

Detailed Explanation

Both APIs provide origin-scoped string key-value storage with a similar interface. localStorage generally persists until the data is explicitly removed, while sessionStorage is scoped to a particular browser tab or page session and is cleared when that session ends.

Both are synchronous browser storage mechanisms. Neither should be treated as a secure location for sensitive data simply because the values are not displayed on the page.

Code Example

localStorage.setItem("theme", "dark");
sessionStorage.setItem("step", "2");

console.log(localStorage.getItem("theme"));
console.log(sessionStorage.getItem("step"));