JavaScript·100 questions

What is the difference between localStorage and sessionStorage?

Answer

The difference between localStorage and sessionStorage lies in the lifespan and scope of the saved data, although both of these mechanisms provide an identical API for working with the browser's web storage. localStorage is designed for long-term data storage. Information written to localStorage is saved indefinitely—it is not deleted when the tab or browser is closed and will be available during subsequent user visits to the site until the data is erased programmatically via code or manually through browser settings.

sessionStorage works differently and is oriented towards temporary data storage within a single specific tab or browser window. Data in sessionStorage lives only as long as the tab in which it was created remains open. As soon as the user closes this tab or browser window, all information in sessionStorage is irreversibly deleted. If the user opens the same page in a new tab, it will have a completely new and empty sessionStorage, even if the domain remains the same.

Both storages have similar memory capacity limitations, which usually range from 5 to 10 megabytes depending on the specific browser. Both the first and second storages support the same set of methods: setItem, getItem, removeItem, clear, and also work exclusively with strings, requiring the use of JSON.stringify and JSON.parse to save objects and arrays.

Synchronicity of operations is characteristic of both types of storages: all read and write requests are executed in the main JavaScript thread in a blocking manner. The choice between them depends on business logic: localStorage is ideal for saving user theme settings, authorization tokens, or an online store shopping cart, while sessionStorage is indispensable for temporary data, such as multi-step form state, current session filter data, or protection against duplicate request submissions, which should not carry over between different tabs of the same site.

Was this answer helpful?

More questions in this topic

Related questions from other topics