
Local Storage and Session Storage in JS
Local Storage and Session Storage are two types of web storage that allow you to store data locally in a user's browser. They are both part of the Web Storage API, which provides a way to store data in a web application. Local Storage and Session Storage are used to store data that can be accessed by a web application, but they have some key differences. Local Storage stores data for a longer period of time, while Session Storage stores data for a shorter period of time. Local Storage is also more secure than Session Storage, as it is encrypted and can only be accessed by the user who created the data. Session Storage, on the other hand, is less secure and can be accessed by anyone who has access to the user's browser.
Example:-
localStorage.setItem("name", "John");
console.log(localStorage.getItem("name")); // "John"Local Storage API: All Methods
1. localStorage.setItem(key, value)
localStorage.setItem("username", "Ram");Local Storage API: All Methods
1. localStorage.setItem(key, value)
localStorage.setItem("username", "Ram");2. localStorage.getItem(key)
localStorage.getItem("usernam ");3. localStorage.removeItem(key)
localStorage.removeItem("usernam ");4. localStorage.clear()
localStorage.clear();5. localStorage.length
localStorage.length;6. localStorage.key(index)
localStorage.key(0);Limitations of Local Storage
What is sessionStorage?
sessionStorage is a property of the Window interface that allows you to store data locally in a user's browser. It is similar to localStorage, but it stores data for a shorter period of time . The data stored in sessionStorage is deleted when the user closes the browser or the tab. It is also less secure than localStorage, as it is not encrypted and can be accessed by anyone who has access to the user's browser.
Example:-
sessionStorage.setItem(" name", "John"); sessionStorage API: All Methods
1. sessionStorage.setItem(key, value)
sessionStorage.setItem(" username", "Ram");2. sessionStorage.getItem(key)
sessionStorage.getItem(" username ");3. sessionStorage.removeItem(key)
sessionStorage.removeItem(" username ");4. sessionStorage.clear()
sessionStorage.clear(); sessionStorage vs localStorage vs cookies
Here is a comparison of the three:
| Feature | sessionStorage | localStorage | Cookies |
|---|---|---|---|
| Lifetime | Tab-close | Until cleared manually | Set via expires/max-age |
| Capacity | ~5MB | ~5MB | ~4KB |
| Sent to server? | No | No | Yes |
| Tab-specific? | Yes | No (shared across tabs) | No |
| Auto expire? | Yes (on tab close) | No | Yes |
| Secure storage? | No | No | With HttpOnly |