1console.log("hello-world);
console.log("hello-world);
.container {
width: 80%;
}
<pre><code class="language-css">
.container {
width: 80%;
}
</code></pre>
1console.log("hello-world);
console.log("hello-world);
.container {
width: 80%;
}
<pre><code class="language-css">
.container {
width: 80%;
}
</code></pre>
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.
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.
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
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.
Now that we understand the basics, let’s dive into various techniques to iterate over all keys stored in localStorage.
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)
: Converts localStorage
into an array of key-value pairs.for (const [key, value] of ...)
: Destructures each pair, allowing easy access to both the key and value.for
loopUsing 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 in localStorage
.localStorage.key(i)
: Gets the key at the specified index.localStorage.getItem(key)
: Retrieves the value associated with the given key.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);
});
localStorage
for…in
: Due to Inherited PropertiesThe 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.customProperty
will be included in the loop, which is not intended behavior.for...of
, Object.entries()
, or Object.keys()
. These methods specifically target the object’s own enumerable properties, and avoids unexpected inherited properties.localStorage
(usually 5MB per domain). Attempting to exceed this limit may result in a QUOTA_EXCEEDED_ERR
.localStorage
stores data as strings. When storing complex data types (e.g., objects or arrays), make sure to serialize them using JSON.stringify()
before storing and deserialize them using JSON.parse()
when retrieving.localStorage
. Always check for support before relying on it.localStorage
.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.
Problem (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! 🚀
Feel free to reach out!