How does localStorage differ from sessionStorage in JavaScript?
Asked on Aug 16, 2024
Answer
LocalStorage and sessionStorage are both part of the Web Storage API, used to store data on the client side. The key difference lies in their lifespan and scope.
// Storing data in localStorage
localStorage.setItem("key", "value");
// Retrieving data from localStorage
const localValue = localStorage.getItem("key");
// Storing data in sessionStorage
sessionStorage.setItem("key", "value");
// Retrieving 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 retains data for the duration of the page session, which ends when the page is closed.
- Both storage types store data as key-value pairs and have a similar API.
- Data stored in localStorage and sessionStorage is specific to the protocol of the page (http or https).
Recommended Links:
← Back to All Questions