Local storage and session storage are both web storage options available in modern web browsers, but they have some key differences.
- Scope:
- Local storage: The data stored in local storage persists even after the browser is closed and reopened. It has a global scope and can be accessed by any page from the same origin (domain).
- Session storage: The data stored in session storage is available only for the duration of the browser session. It is limited to the specific tab or window and is cleared when the session ends or the browser is closed.
- Storage Limit:
- Local storage: The maximum storage limit for local storage is typically around 5MB per domain. It provides more storage space compared to session storage.
- Session storage: The maximum storage limit for session storage is also around 5MB per domain, but it may vary slightly depending on the browser.
- Accessibility:
- Local storage: The data stored in local storage can be accessed by any JavaScript code running on the same domain. It is accessible across different windows, tabs, and iframes from the same origin.
- Session storage: The data stored in session storage is accessible only within the same tab or window. It cannot be accessed by JavaScript code running in other tabs or windows from the same origin.
To demonstrate the usage of local storage and session storage in JavaScript, here’s an example in HTML format:
<!DOCTYPE html> <html> <head> <title>Web Storage Example</title> </head> <body> <script> // Local Storage Example localStorage.setItem('name', 'John'); console.log(localStorage.getItem('name')); // Output: John // Session Storage Example sessionStorage.setItem('age', '25'); console.log(sessionStorage.getItem('age')); // Output: 25 </script> </body> </html>
In the above example, we use localStorage
to store the name ‘John’ and sessionStorage
to store the age ‘25’. We can retrieve the stored values using getItem()
method and display them in the console.