JavaScript localStorage and sessionStorage: Essential Guide
What are localStorage and sessionStorage?
localStorage ensures that data is persistently stored even if the browser window or tab is closed. In contrast, sessionStorage only retains data while the browser window or tab is open, automatically deleting the data when the window or tab is closed.
Differences between localStorage and sessionStorage
The fundamental difference lies in how long the data is stored. Data in localStorage remains persistent even when the browser window or tab is closed, while sessionStorage is valid only as long as the browser window or tab is open. Consequently, localStorage is suitable for long-term storage, whereas sessionStorage is used for short-term storage.
Examples of Using localStorage and sessionStorage
// Saving Data
localStorage.setItem('key', 'value');
sessionStorage.setItem('key', 'value');
localStorage.setItem('name', 'Alice');
sessionStorage.setItem('name', 'Alice');
// Reading Values
localStorage.getItem('key');
sessionStorage.getItem('key');
var valueFromSession = sessionStorage.getItem('name');
var valueFromLocal = localStorage.getItem('name');
console.log(valueFromSession); // Output: Alice
console.log(valueFromLocal); // Output: Alice
// Removing Data
localStorage.removeItem('key');
localStorage.removeItem('key');
sessionStorage.removeItem('name');
sessionStorage.removeItem('name');
With these examples, understanding how localStorage and sessionStorage are used will be easier.