The HTML Web Storage API provides a way to store data in a user’s browser that persists even after the browser is closed or the user navigates away from the page. The API consists of two storage mechanisms:
- Local Storage: It stores data with no expiration date and it is available across browser sessions and tabs. The data is stored in key-value pairs and can be accessed using JavaScript.
- Session Storage: It stores data for a single session, meaning that the data is lost when the browser is closed or the session ends. Like local storage, the data is stored in key-value pairs and can be accessed using JavaScript.
The Web Storage API is easy to use and requires only a few lines of code to get started. Here’s an example of how to store and retrieve data using the Local Storage API:
// Store data
localStorage.setItem('key', 'value');
// Retrieve data
const value = localStorage.getItem('key');
console.log(value); // Output: 'value'
And here’s an example of how to store and retrieve data using the Session Storage API:
// Store data
sessionStorage.setItem('key', 'value');
// Retrieve data
const value = sessionStorage.getItem('key');
console.log(value); // Output: 'value'
Both Local Storage and Session Storage have limitations on the amount of data that can be stored (typically around 5-10 MB) and they only support storing data in string format, so you’ll need to use JSON.stringify() and JSON.parse() to store and retrieve more complex data types like arrays and objects.
