Client-Side Storage in Javascript
sessionStorage is another type of client-side storage provided by modern browsers. Similar to localStorage, it allows web applications to store data locally on a user's device. However, sessionStorage differs in that it provides temporary storage that is cleared once the browser session ends, i.e., when the browser tab or window is closed.
sessionStorage.setItem('key', 'value');
This code snippet stores a key-value pair ('key' as the key and 'value' as the corresponding value) in the sessionStorage of the browser. The data will be available only for the duration of the browser session.
const data = sessionStorage.getItem('key');
This code retrieves the value associated with the key 'key' from the sessionStorage and stores it in the variable 'data'. It allows you to access previously stored data from sessionStorage within the current browser session.
sessionStorage.removeItem('key');
This code removes the key-value pair with the key 'key' from the sessionStorage. After execution, the data associated with the specified key will no longer be available in the sessionStorage.
sessionStorage.clear();
This code clears all the data stored in the sessionStorage of the browser. It removes all key-value pairs, effectively resetting the sessionStorage to an empty state, but only for the current browser session.
sessionStorage offers various use cases in web applications:
Despite its usefulness, sessionStorage has limitations similar to localStorage: