Middle+
What is the difference between sessionStorage and localStorage?
sobes.tech AI
Answer from AI
sessionStorage and localStorage are two types of web storage provided by the browser for storing data on the client side, but they differ in lifespan and scope:
-
sessionStorage stores data only within a single browser tab session. Data is removed when the tab or window is closed. Data is not accessible across different tabs or windows.
-
localStorage stores data without expiration until it is manually cleared by the user or the script deletes it. Data is accessible across all tabs and windows of the same domain.
Example usage:
// Write data
localStorage.setItem('key', 'value');
sessionStorage.setItem('key', 'value');
// Read data
console.log(localStorage.getItem('key'));
console.log(sessionStorage.getItem('key'));
Thus, sessionStorage is suitable for temporary data related to a single session, while localStorage is used for long-term storage of settings or cache.