Storage Keys and Enumeration
You'll learn how to loop through all items stored in localStorage or sessionStorage using the length property and key() method.
The Core Idea
So far you've accessed storage items by name when you already knew the key. But what if you need to discover what's stored or process every item? Web Storage provides two tools for this: the length property tells you how many items exist, and the key() method retrieves a key name by its numeric position.
Think of it like a filing cabinet where you can ask "How many folders are in here?" (length) and "What's the name of the 3rd folder?" (key(2)) — allowing you to systematically examine every folder without knowing their names in advance.
How It Works
The localStorage.length property returns the total number of stored items. The localStorage.key(index) method takes a number (starting from 0) and returns the key name at that position. Combine them in a loop to enumerate everything:
// Assume we have some stored items
localStorage.setItem('username', 'Alice');
localStorage.setItem('theme', 'dark');
localStorage.setItem('score', '1500');
// Enumerate all keys and values
for (let i = 0; i < localStorage.length; i++) {
const keyName = localStorage.key(i);
const value = localStorage.getItem(keyName);
console.log(`${keyName}: ${value}`);
}
// Logs each key-value pair
The order of keys is not guaranteed, so don't rely on insertion order. This technique is useful for debugging, clearing specific patterns, or migrating storage data.
You can also build an array of all keys:
const allKeys = [];
for (let i = 0; i < localStorage.length; i++) {
allKeys.push(localStorage.key(i));
}
console.log(allKeys); // ['username', 'theme', 'score']
Key Takeaway: Use localStorage.length and localStorage.key(index) together to systematically iterate through all stored items when you don't know the key names in advance.