Explain Codes LogoExplain Codes Logo

Looping through localStorage in HTML5 and JavaScript

javascript
localStorage
serialization
deserialization
Nikita BarsukovbyNikita Barsukov·Oct 5, 2024
TLDR

To iterate over localStorage using for loop and access key-value pairs using .key() and .getItem() methods:

for (let i = 0; i < localStorage.length; i++) { console.log(localStorage.key(i), localStorage.getItem(localStorage.key(i))); }

This operation logs each key-value pair demonstrating direct enumeration and retrieval.

Non-stringy business: dealing with non-string data

localStorage is built for storing string values. Storing arrays or objects requires serialization using JSON.stringify and deserialization using JSON.parse:

// Parking an object in localStorage (I assure you, it's legal...mostly) localStorage.setItem('userData', JSON.stringify({ name: 'John', age: 30 })); // Retrieving the parked object (It stayed put, yay!) let userData = JSON.parse(localStorage.getItem('userData')); console.log(userData.name); // outputs: John

Not all browsers fully support the structured clone algorithm for non-string data, hence the JSON twist.

Iterating the lot: useful patterns and common pitfalls

No, no, no to for...in!

Despite for...in appearing attractive for iterations, not advisable for localStorage. It's designed for general objects, not Storage objects, and could get you into a thick soup.

Keys, please! Using Object.keys()

To get all keys from localStorage, use Object.keys(). It returns an array, enabling use of array methods like .forEach(), .map(), and .filter():

Object.keys(localStorage).forEach((key) => { // Aha! A key not under the doormat! console.log(key, localStorage.getItem(key)); });

Pair them up with Object.entries()

Object.entries() provides an array of key-value pairs for direct iteration:

Object.entries(localStorage).forEach(([key, value]) => { // Key and value, sitting in a tree, K-I-S-S-I--wait. console.log(key, value); // outputs: key and raw string value });

jQuery's looping

If jQuery is your weapon of choice, $.each is your armour:

$.each(localStorage, (key, value) => { // With jQuery, we trusty! console.log(key, value); });

Chrome's local speciality

Chrome has a local flavour allowing for direct iteration over localStorage objects without needing .key():

for (let key in localStorage) { if (localStorage.hasOwnProperty(key)) { // Chrome, Chrome, on the wall, who's the fairest of them all? console.log(key, localStorage[key]); } }

Dealing with the quirky and special cases

Saving the order: Arrays to the rescue!

To guarantee order, serialize an array instead of individual items. Arrays never forget their order (unless you scramble them):

// Storing an array let items = ['item1', 'item2', 'item3']; localStorage.setItem('items', JSON.stringify(items)); // Retrieving and spinning over the array items = JSON.parse(localStorage.getItem('items')); items.forEach((item) => { console.log(item); // Outputs: item1, item2, item3 in that order });

Are we compatible? Browser check!

Check browser compatibility for localStorage and serialization methods in case of older browsers or restrictive settings:

if (typeof Storage !== 'undefined') { // You've got storage action! } else { // Alas! No web storage support for this one. }

The important stuff: Storing complex data

Shy away from splitting a single string for storage. Instead, smartly use structured data with unique keys for efficient access. Be cautious with quota limits (typically 5MB) and take note of browser policies that could mess with your merry storage plans.