What are LocalStorage And SessionStorage in the browser?
LocalStorage and SessionStorage are both web storage APIs that allow a web page to store data locally in the user’s browser. They provide an easy way for a web page to store data that can be used across multiple page loads and sessions.
LocalStorage is a property of the window object, which means it is accessible from any script running in the current context. It allows you to store data as key-value pairs, where the data is persisted even after the browser is closed. This makes it suitable for storing data that needs to be accessed across multiple sessions, such as user preferences or settings.
SessionStorage is similar to LocalStorage, but the data is stored in a separate storage area for each origin and is only available within the current browser tab or window. When the user closes the tab or window, the data is deleted. This makes it suitable for storing data that is only needed for the duration of the session, such as a shopping cart or form data that is being entered but not yet submitted.
Both LocalStorage and SessionStorage are simple to use. To store data, you can use the setItem() method, which takes a key and a value as arguments. To retrieve the data, you can use the getItem() method, which takes the key as an argument and returns the value. You can also use the removeItem() method to delete data from the storage area.
Here is an example of how to use LocalStorage:
// Store a value in LocalStorage
localStorage.setItem("key", "value");
// Retrieve the value from LocalStorage
let value = localStorage.getItem("key");
// Remove the value from LocalStorage
localStorage.removeItem("key");SessionStorage works in a similar way, with the same methods available for storing, retrieving, and deleting data. Here is an example of how to use sessionStorage:
// Store a value in SessionStorage
sessionStorage.setItem("key", "value");
// Retrieve the value from SessionStorage
let value = sessionStorage.getItem("key");
// Remove the value from SessionStorage
sessionStorage.removeItem("key");Both LocalStorage and SessionStorage are useful for storing small amounts of data that need to be accessed across multiple page loads or sessions. They are a good alternative to cookies, which have limited size and are sent with every HTTP request, making them less efficient for storing larger amounts of data.
