Understanding localStorage is crucial for developers working with web applications. This local storage solution enables the storage of key-value pairs in a user’s browser, persisting data even after the browser is closed. In this guide, we’ll explore various techniques for iterating over localStorage keys and also common mistakes.
What is localStorage()
localStorage
is a web storage API that allows developers to store key-value pairs locally in a user’s browser. This storage persists even after the browser is closed and reopened, making it ideal for saving user preferences, settings, and more.
Demo: Setting and Retrieving from localStorage
Let’s start with a quick demonstration of how to set and retrieve values in localStorage
. We can use setItem()
to store a value associated with a key, and getItem()
to retrieve it.
// Set a value
localStorage.setItem('username', 'coder123');
// Retrieve a value
const storedUsername = localStorage.getItem('username');
console.log(storedUsername); // Output: coder123
Can localStorage be Used Across Tabs?
Yes, localStorage is shared across tabs with the same origin. Each tab has access to the same localStorage data. If you need to communicate between tabs, localStorage can be a suitable solution for sharing persistent data.
Iterating over localStorage Keys
Now that we understand the basics, let’s dive into various techniques to iterate over all keys stored in localStorage.
Method 1: Using Object.entries()
Object.entries()
converts localStorage
into an array of key-value pairs, making iteration straightforward.
for (const [key, value] of Object.entries(localStorage)) {
console.log(key, value);
}
Explanation:
Object.entries(localStorage)
: ConvertslocalStorage
into an array of key-value pairs.for (const [key, value] of ...)
: Destructures each pair, allowing easy access to both the key and value.
Method 2: Using a for
loop
Using a classic for
loop over the length of localStorage
, we can fetch all the keys and values .
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
const value = localStorage.getItem(key);
console.log(key, value);
}
Explanation:
localStorage.length
: Retrieves the number of items inlocalStorage
.localStorage.key(i)
: Gets the key at the specified index.localStorage.getItem(key)
: Retrieves the value associated with the given key.
Method 3: Using forEach()
Just another loop variant. We can use the Object.keys()
to extract keys and then iterate on those keys using forEach()
.
Object.keys(localStorage).forEach(key => {
const value = localStorage.getItem(key);
console.log(key, value);
});
⚠ Common errors related to localStorage
Avoid for…in
: Due to Inherited Properties
The problem with for…in
is that it doesn’t distinguish between the object’s own properties and inherited properties. This can lead to unexpected behavior, especially when the Object.prototype
has been extended.
Object.prototype.customProperty = 'I should not be here!';
// Incorrect usage of for...in
for (const key in localStorage) {
console.log(key, localStorage[key]);
}
Object.prototype.customProperty
: Extends the prototype with an additional property.- The
customProperty
will be included in the loop, which is not intended behavior. - To avoid this issue, opt for other iteration methods such as
for...of
,Object.entries()
, orObject.keys()
. These methods specifically target the object’s own enumerable properties, and avoids unexpected inherited properties.
Storage Capacity Exceeded
- Explanation: Browsers impose a storage limit for
localStorage
(usually 5MB per domain). Attempting to exceed this limit may result in aQUOTA_EXCEEDED_ERR
. - Best Practice: Always check the remaining storage capacity before attempting to store large amounts of data.
Data Serialization
- Explanation:
localStorage
stores data as strings. When storing complex data types (e.g., objects or arrays), make sure to serialize them usingJSON.stringify()
before storing and deserialize them usingJSON.parse()
when retrieving. - Best Practice: Use serialization and deserialization consistently to avoid unexpected behavior.
No Storage Support
- Explanation: Some browsers or browser settings may disable
localStorage
. Always check for support before relying on it. - Best Practice: Provide alternative storage solutions or gracefully handle the absence of
localStorage
.
🧪Practice Coding Problem: Storage Explorer 💾🔍
In the spirit of Test Driven Development ( 😁), lets test our understanding by solving a problem.
Apply your newfound knowledge with a practical problem. Write a function
exploreLocalStorage()
that logs all key-value pairs inlocalStorage
. Use any method you prefer.JavaScript/** * Explore and log all key-value pairs in localStorage. */ function exploreLocalStorage() { // > > > 👉 Write code here 👈 < < < } // Seed localStorage with sample values localStorage.setItem('username', 'coder123'); localStorage.setItem('theme', 'dark'); localStorage.setItem('isLogged', 'true'); // Driver code exploreLocalStorage(); // Output: username coder123 // theme dark // isLogged true // ...
Please attempt before seeing the Answer:
/**
* Explore and log all key-value pairs in localStorage.
*/
function exploreLocalStorage() {
for (const [key, value] of Object.entries(localStorage)) {
console.log(key, value);
}
}
Hopefully, this blog will help you to create better browser applications, while using user’s localStorage
data. Keep coding! 🚀