localStorage
Remember between visits.
Reload the to do list, and every task vanishes, because variables only live while the page is open. Local storage is a small store in the browser that keeps data between visits, even after the browser is closed.

- Reload, tasks vanish
- Variables don't last
- localStorage does
Saving and loading
Set item saves a value under a key. Local storage only stores strings, so we turn our array into JSON first. When the page loads, get item reads it back, and JSON parse turns it into an array again. If nothing's saved yet, we start with an empty array. We added two notes, then reloaded the page, and they're still there.
<link rel="stylesheet" href="style.css">
<form id="form"><input id="note"> <button>Save</button></form>
<ul id="list"></ul>
<script>
const notes = JSON.parse(localStorage.getItem("notes") ?? "[]");
function render() {
list.replaceChildren(...notes.map(n => {
const li = document.createElement("li"); li.textContent = n; return li;
}));
}
form.onsubmit = (e) => {
e.preventDefault();
notes.push(note.value); note.value = "";
localStorage.setItem("notes", JSON.stringify(notes));
render();
};
render();
</script>Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#f7df1e;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} .big{font-size:64px;font-weight:800}Also uses actions.json
[{"type": "#note", "text": "Pay rent"}, {"key": "Enter"}, {"type": "#note", "text": "Book dentist"}, {"key": "Enter"}, {"reload": true}]Good to know
Local storage holds a few megabytes per website, and it's only on that one browser. Never store passwords or secrets in it, since any script on the page can read it. Remove item deletes one key. Session storage works the same way, but forgets everything when the tab closes.
| key | value |
|---|---|
| setItem(key, str) | save |
| getItem(key) | load, or null |
| JSON | for arrays and objects |
| No secrets | scripts can read it |
Summary
Local storage saves strings between visits. Use JSON stringify to save arrays and objects, and JSON parse to load them. Next, handling events on many elements at once.
Key takeaways- localStorage.setItem
- getItem ?? default
- JSON for objects