I am trying to make a basic notes app using JS.
I am storing notes in localStorage, and I am trying to print those notes using for-in loop. It works mostly fine, but I don’t know why I am getting extra values like length, getItem, key, etc. Can anyone help?
My code:
for (const key in localStorage) {
let notes = document.getElementById("notes");
let value = localStorage.getItem(key);
notes.innerHTML = notes.innerHTML + `${key}: ${value} <br>`;
}
localStorage(and likewisesessionStorage) is an object similar toMap, in that its own properties and methods don’t directly correspond to values actually kept in the storage. Enumerating its properties and accessing missing properties on it will fall back to returning items from the underlying storage, but that is actually a design flaw that is best not relied on.To enumerate the contents of a storage object (
localStorageorsessionStorage), you shouldn’t usefor-in,Object.keysorObject.entries. Usekey,lengthandgetItem:Using the
for-inloop and property accesses will return properties of thelocalStorageobject itself, while usingObject.entriesorObject.keyswill skip them even if there actually are storage items with the same keys. For example:As an aside though, keep in mind that each storage object provides a single namespace shared by all scripts that happen to be running on your page. If any other script you use decides to store items in
localStorageas well, those may appear as ‘notes’ in your app, and modifying them may corrupt those other scripts’ data. You may be better off at the very least prefixing (or suffixing) storage keys you use with something specific to your app, to section them off and minimise the risk of clashes.