What is the difference between localStorage and sessionStorage?
They are the same API with the same two storage areas, and they differ in lifetime and scope.
Local storage is permanent. The data stays until something explicitly removes it, and it is shared by every page on the origin, in every tab. Session storage is scoped to the browsing context. Each tab gets its own copy, so two tabs of the same site do not see each other's session data, and the data is discarded when the tab is closed. A page opened in a new tab from a link starts with an empty session storage.
// Web storage only exists in a browser.
if (typeof localStorage !== "undefined") {
localStorage.setItem("theme", "dark");
sessionStorage.setItem("theme", "light");
console.log(localStorage.getItem("theme")); // "dark"
console.log(sessionStorage.getItem("theme")); // "light"
// Both store strings only.
localStorage.setItem("count", 42);
console.log(typeof localStorage.getItem("count")); // "string"
// The keys and the length.
console.log(localStorage.length);
console.log(localStorage.key(0));
// Removing an item.
localStorage.removeItem("theme");
console.log(localStorage.getItem("theme")); // null
} else {
console.log("No web storage in this runtime - open a browser console to try it.");
}Both store strings only, so anything else has to be converted on the way in and parsed on the way out. That is why you see the JSON pattern in most code that stores objects, and why you have to handle the case where the stored text is not valid JSON.
The API is the same for both. The setItem, getItem, removeItem and clear methods, plus the length property and the key method. The one difference in the API itself is that reading a missing key gives you null rather than an error.
Both are synchronous, and that matters. Every read and write blocks the main thread while it happens, so a large amount of data or a lot of frequent writes will make the page janky. The values are also stored as text, so there is a practical size limit of a few megabytes per origin for local storage.