Client-Side Storage in Javascript
localStorage is a type of client-side storage provided by modern browsers. It allows web applications to store data locally on a user's device, offering persistent storage even after the browser is closed and reopened. It stores the data in key-value pairs where key is the string to indentify the data and the value is the actual data itself stored as a string.
localStorage.setItem('key', 'value');
This stores a key-value pair ('key' as the key and 'value' as the corresponding value) in the localStorage of the browser. This data will persist even after the browser is closed and reopened.
const data = localStorage.getItem('key');
It will retrieve the value associated with the key 'key' from the localStorage and stores it in the variable 'data'. It allows you to access previously stored data from localStorage.
localStorage.removeItem('key');
It will remove the key-value pair with the key 'key' from the localStorage. After execution, the data associated with the specified key will no longer be available in the localStorage.
localStorage.clear();
It will clear all the data stored in the localStorage of the browser. It removes all key-value pairs, effectively resetting the localStorage to an empty state.
const user = { name: 'John Doe', age: 25 } localStorage.setItem('user', JSON.stringify(user));
To store complex data such as objects or arrays in localStorage, you first need to convert the data into a string using JSON.stringify() method. This ensures that the data is stored in a format that can be easily retrieved and parsed later.
const storedData = localStorage.getItem('user'); const userData = JSON.parse(storedData);
This code retrieves the complex data stored in localStorage under the key 'user' and parses it back into a JavaScript object. Now, the variable userData
contains the user object with properties like name and age.
localStorage provides several advantages and can be used in various scenarios with web applications:
While convenient, localStorage comes with certain limitations: