Javascript local storage
Created By: chatGPT
Local storage provides a way to store data on the client side in the user's web browser. It is part of the Web Storage API and allows web applications to save data as key-value pairs. Unlike cookies, local storage has a much larger capacity and does not get sent with every HTTP request.
// Check if Local Storage is supported
if (typeof(Storage) !== 'undefined') {
// Code for localStorage feature available
} else {
// No Web Storage support
}
To set an item in local storage, you use the
setItem()
method, which takes two arguments: the key and the value. The value should be a string. If you want to store objects, you'll need to convert them to a string using JSON.stringify()
.const user = {
name: 'John Doe',
age: 30
};
localStorage.setItem('user', JSON.stringify(user));
To retrieve an item, use the
getItem()
method by passing the key. You should also parse the string back into an object if you stored it that way by using JSON.parse()
.const storedUser = localStorage.getItem('user');
if (storedUser) {
const userObject = JSON.parse(storedUser);
console.log(userObject.name); // Output: John Doe
}
You can remove an item from local storage using the
removeItem()
method. Simply provide the key for the item you want to delete.localStorage.removeItem('user');
If you want to clear all items in local storage, use the
clear()
method. This will empty the entire local storage for your origin.localStorage.clear();
To check the size of data stored in local storage, you can use the
length
property. This can be useful for managing and optimizing your data storage.let totalItems = localStorage.length;
console.log(totalItems);
Be aware that local storage is synchronous, which means it can affect the performance of your application if used excessively. Always consider the amount of data you are storing and manage it appropriately.
// Caution with large amounts of data
const data = 'long string data...';
localStorage.setItem('largeData', data);