Web storage is a feature in web browsers that allows websites to store data locally on a user’s device. It provides a way to persistently store key-value pairs in the form of strings. The two main types of web storage are localStorage and sessionStorage.
localStorage: This type of web storage allows data to be stored with no expiration date. The data stored in localStorage remains available even after the browser is closed and reopened. It can be accessed by any page within the same domain.
sessionStorage: This type of web storage is similar to localStorage, but the data stored in sessionStorage is only available for the duration of the session. Once the browser is closed, the data is cleared. sessionStorage is specific to each tab or window and cannot be accessed by other tabs or windows.
To interact with web storage using JavaScript, we can use the following methods:
setItem(key, value)
: This method allows us to store a key-value pair in web storage. The key is a string that serves as the identifier, and the value can be any string. For example,localStorage.setItem('username', 'John')
stores the value ‘John’ with the key ‘username’ in localStorage.getItem(key)
: This method retrieves the value associated with a given key from web storage. For example,localStorage.getItem('username')
returns the value ‘John’ if it exists in localStorage.removeItem(key)
: This method removes the key-value pair associated with a given key from web storage. For example,localStorage.removeItem('username')
removes the key-value pair with the key ‘username’ from localStorage.clear()
: This method clears all the key-value pairs stored in web storage. For example,localStorage.clear()
removes all the data stored in localStorage.
Here’s an example of using web storage in JavaScript and displaying the result in HTML format:
<!DOCTYPE html> <html> <head> <title>Web Storage Example</title> </head> <body> <script> // Storing data in localStorage localStorage.setItem('username', 'John'); // Retrieving data from localStorage var username = localStorage.getItem('username'); // Displaying the result in HTML document.body.innerHTML = 'Username: ' + username; </script> </body> </html>
In the above example, the value ‘John’ is stored with the key ‘username’ in localStorage. Then, it is retrieved using localStorage.getItem('username')
and displayed on the webpage as “Username: John”.