Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
What is the difference between localStorage and sessionStorage in JavaScript?
Asked on May 17, 2026
Answer
LocalStorage and sessionStorage are both part of the Web Storage API, allowing you to store data in the browser. The key difference is in their persistence and scope.
// Store data in localStorage
localStorage.setItem("key", "value");
// Retrieve data from localStorage
const localValue = localStorage.getItem("key");
// Store data in sessionStorage
sessionStorage.setItem("key", "value");
// Retrieve data from sessionStorage
const sessionValue = sessionStorage.getItem("key");Additional Comment:
✅ Answered with JavaScript best practices.- localStorage persists data even after the browser is closed and reopened, making it suitable for long-term storage.
- sessionStorage only persists data for the duration of the page session. Once the tab or window is closed, the data is cleared.
- Both localStorage and sessionStorage store data as key-value pairs and have a similar API for setting, getting, and removing items.
- Data stored in either storage type is specific to the protocol of the page (http or https) and is not shared across different domains.
Recommended Links:
