Iterating over all keys stored in local storage using JavaScript

There are many ways to iterate through all keys stored in a localStorage object using JavaScript.

The quickest way is to use the for loop to iterate over all keys just like an array:

for (let i = 0; i < localStorage.length; i++) {
  const key = localStorage.key(i)
  console.log(`${key}: ${localStorage.getItem(key)}`)
}

Another way is to use the for...in loop to iterate over all keys of the localStorage object:

for (const key in localStorage) {
  console.log(`${key}: ${localStorage.getItem(key)}`)
}

The above code snippet iterates over all keys stored in localStorage and prints them on the console. However, it also outputs the built-in localStorage properties like length, getItem, setItem, and so on.

To filter-out the object prototype's own properties, you can use the hasOwnProperty() method as shown below:

for (const key in localStorage) {
  // Skip built-in properties like length, setItem, etc.
  if (localStorage.hasOwnProperty(key)) {
    console.log(`${key}: ${localStorage.getItem(key)}`)
  }
}

Finally, the last way is to use the Object.keys() method to collect all "own" keys of localStorage and then loop over them by using the for...of loop:

const keys = Object.keys(localStorage)
for (let key of keys) {
  console.log(`${key}: ${localStorage.getItem(key)}`)
}

Read this article to learn more about HTML web storage API and how to use localStorage and sessionStorage objects to store information in the user's browser.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.