Web Storage Key Enumeration
The Web Storage API lets frontend code enumerate stored keys using `Storage.length` and `Storage.key()`. This works with both `localStorage` and `sessionStorage`, whose values are exposed through the `Storage` interface.
`Storage.length` reports how many key/value entries are currently stored. It is useful when you need to iterate through all entries rather than access a known key directly.
`Storage.key(index)` returns the key at a numeric position. Valid indexes range from `0` through `length - 1`; an invalid index returns `null`.
Because storage is key/value based, enumeration gives you keys first, after which `getItem()` can retrieve the corresponding values. The ordering of keys should not be treated as an application-level ordering guarantee.
The same enumeration pattern applies to `localStorage` and `sessionStorage`. Code should also tolerate an empty storage area, where `length` is `0` and the loop simply performs no iterations.
Key points
- Use `Storage.length` to determine how many stored keys exist.
- Use `Storage.key(index)` to retrieve a key by numeric index.
- Iterate from `0` to `length - 1` to enumerate all keys.
- `key()` returns `null` for an invalid index.
- The pattern applies to both `localStorage` and `sessionStorage`.
Interview questions
How do you enumerate all keys in `localStorage`?
Read `localStorage.length` to determine the number of entries. Then loop over indexes from `0` to `length - 1` and call `localStorage.key(i)`. Each returned key can be passed to `getItem()` when its value is needed.
What does `Storage.key(index)` return?
It returns the key associated with the supplied numeric index in the storage area. Indexing starts at zero. If the index does not identify an entry, the method returns `null`.
Can you enumerate both `localStorage` and `sessionStorage` the same way?
Yes. Both objects implement the `Storage` interface, which provides `length`, `key()`, `getItem()`, `setItem()`, `removeItem()`, and `clear()`. Therefore, the same key-enumeration pattern can be applied to either storage area.
Why should application code avoid depending on the order returned by `key()`?
The purpose of `key()` is to expose a key at an index, not to provide an application-defined ordering mechanism. Code that depends on a particular sequence can therefore become fragile when entries change. If ordering matters, the application should store or construct an explicit ordering rather than infer one from storage enumeration.