Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JS LocalStorage – Why am i getting extra values with for in loop

i am trying to make a basic notes app using js a i have stored notes in local storage and i am trying to print those note using for in loop everything is fine but i dont know why am i getting extra values like length, getItem, key etc can anyone help

my code

(function () {
for (key in localStorage) {
    let notes = document.getElementById("notes")
    let value = localStorage.getItem(key)
    notes.innerHTML = notes.innerHTML + `${key}: ${value} <br>`
}
})();

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

localStorage contains key/value pairs similar to a JS object with some built in functions such as setItem and getItem. In order to iterate over everything in localStorage you would have to do it the same way you would with a JS object. Here is one way to do it.

 for (const [key, value] of Object.entries(localStorage)) {
   console.log(key, value);
 }

This would log the keys and values of each item saved in the localStorage

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading