How to Loop Through LocalStorage in JavaScript

As the capabilities of the browsers increase, local storage has remained a solid feature for storing non-pertinent information. Data that doesn’t need to be stored on a server tends to be saved into local storage.

With multiple pieces of data, there are plenty of uses cases that require iterating through local storage. So, how can you loop through LocalStorage in JavaScript?

Well, this is made relatively simple by the structure of local storage. LocalStorage is essentially just an object. So let’s say we set 3 properties of our local storage:

localStorage.setItem(1, "Tommy Vercetti");
localStorage.setItem(2, "Niko Bellic");
localStorage.setItem(3, "Carl Johnson");

If we examine this data in our dev tools we can the structure of the local storage:

To loop through those items it is as simple as using Object.keys:

Object.keys(localStorage).forEach((key) => {
 console.log(localStorage.getItem(key));
});

This will output the value associated with the current key that we are looping through:

Object.keys will work with any object that has a key value pair and in this case, local storage is no different.

Gareth Dunne

Senior JavaScript Engineer and creator of JSdiaries. Passionate about the latest in web technologies and how it can provide value for my clients.