JavaScript Q&A Logo
JavaScript Q&A Part of the Q&A Network

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:
  • 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).
✅ Answered with JavaScript best practices.
← Back to All Questions