21.1 Saving Data in localStorage
Before you start, create a new Vite project named day21 with the vanilla TypeScript template, exactly as you did on Day 18, and start it with npm run dev. Today’s examples come in three kinds, and each kind goes in a different place:
| The example is… | Where it goes | How you see the result |
|---|---|---|
A page: an .html file and a .dom.ts script |
The HTML goes inside <body> of index.html, in place of <div id="app"></div>; the script replaces src/main.ts |
The browser tab, and its console in the developer tools |
A plain program (load-list.ts) |
Its own file in src/ |
npx tsc, then node src/load-list.ts in the terminal |
Code the checker rejects (set-number.ts) |
Its own file in src/ |
npx tsc only; fix or delete the file after reading it |
As on Day 18, a page’s console.log output appears in the Console tab of the browser’s developer tools (F12).
Every program you have written so far forgets everything when it stops. A Node program’s variables vanish when the last line runs. A page is no better: the moment you reload it, the browser throws away every variable and runs main.ts again from the top. Build the Day 20 task list, add three tasks, press reload, and the list is empty again. For a real app that is useless. Nobody keeps a to-do list that forgets itself.
The browser offers each website a small place to keep data that survives a reload, a closed tab, and even a restart of the computer. It is called localStorage: a store of key-value pairs kept by the browser, where each key is a name you choose (like "name") and each value is the data saved under that name. Think of it as a notebook the browser keeps for your site. Each page in the notebook has a label at the top (the key) and some writing below it (the value). Where the analogy stops: each site gets its own notebook. A page on example.com cannot open the notebook of localhost:5173, and the notebook stays on this one browser on this one computer.
Three methods do almost all the work. Each is called on the global localStorage object, which every page already has:
| Method | What it does |
|---|---|
setItem(key, value) |
Saves value under key, replacing anything saved there before |
getItem(key) |
Gives back the value saved under key, or null if nothing is saved there |
removeItem(key) |
Deletes the key and its value; nothing happens if the key was not there |
Worked example: A page that remembers your name
The page has a paragraph for the greeting and a small form:
<p id="greeting"></p>
<form id="name-form">
<label for="name">Your name</label>
<input id="name" name="name">
<button>Save</button>
</form>The script reads the saved name as soon as the page loads, and saves a new one when the form is submitted:
const greeting = document.querySelector<HTMLParagraphElement>("#greeting");
const form = document.querySelector<HTMLFormElement>("#name-form");
const input = document.querySelector<HTMLInputElement>("#name");
if (greeting === null || form === null || input === null) {
throw new Error("The page is missing an element");
}
const savedName = localStorage.getItem("name");
console.log(savedName);
if (savedName === null) {
greeting.textContent = "Hello, stranger!";
} else {
greeting.textContent = `Welcome back, ${savedName}!`;
}
form.addEventListener("submit", (event) => {
event.preventDefault();
const name = input.value.trim();
localStorage.setItem("name", name);
greeting.textContent = `Nice to meet you, ${name}!`;
console.log(localStorage.getItem("name"));
});Follow it through a first visit, when nothing has been saved yet:
| Line | What happens |
|---|---|
| 1–6 | Day 18’s lookups, with one null check for all three elements |
| 8 | getItem("name") finds no key called "name", so it gives back null |
| 9 | The console shows null |
| 10–11 | savedName is null, so the greeting says Hello, stranger! |
| 16–17 | Nothing more happens until the form is submitted; then Day 20’s preventDefault() stops the reload |
| 18–19 | You typed Ana; setItem writes it into the browser’s notebook under the key "name" |
| 20–21 | The greeting changes, and reading the key straight back shows Ana in the console |
The console shows:
null
Anaand the greeting says Nice to meet you, Ana!.
Now reload the page. Every variable is gone, and the script runs again from line 1, but the notebook is not gone. This time line 8 finds "Ana" under the key, so savedName is the string "Ana", line 13 runs instead of line 11, and the page says Welcome back, Ana!. The console shows:
Ana
That is the whole idea of saving: the program writes data somewhere that outlives it, and the next run reads it back first.
You can look inside the notebook yourself. In Chrome or Edge, open the developer tools, choose the Application tab, and under Local storage click http://localhost:5173; in Firefox the tab is called Storage. You will see a row with the key name and the value Ana. You can also type into the Console tab: localStorage.getItem("name") shows the saved value, and localStorage.setItem("name", "Sam") changes it, which is how you will set up the examples later today. One extra method, localStorage.clear(), deletes every key the site has saved; type it in the console whenever you want to start an example from a first visit.
Why does getItem give null and not an empty string? Because “nothing saved” and “saved an empty string” are different facts, and a program often needs to tell them apart. The checker knows this: in TypeScript, getItem returns string | null, the union from Day 9. So it rejects code that uses the result as if it were always a string:
const savedName = localStorage.getItem("name");
console.log(savedName.toUpperCase());name-possibly-null.ts:2:13 - error TS18047: 'savedName' is possibly 'null'.
This is the same TS18047 you met with querySelector on Day 18. If this code ran on a first visit, null.toUpperCase() would crash with a TypeError. The fix is the same as before: narrow first with === null, as lines 10 to 14 of greeting.dom.ts do, or give a default with ??. Fix or delete this file before you go on.
Key idea
localStorage keeps key-value pairs in the browser between visits. setItem saves, getItem loads (and gives null
when nothing is saved, so its type is string | null), and removeItem deletes.
Watch out
Saving but never loading. A program that calls setItem on every change but never calls getItem when the page starts looks broken: the data is safely in storage (you can see it in the Application tab), yet the page always opens empty. Saving is only half the job. Every saved key needs a matching load at the top of the script.
Pause and try
Question 1 · Multiple choice
A page has never saved anything under the key "score". What does localStorage.getItem("score") give back?
0""null- It throws an error
Check your reasoning
C. getItem gives null when there is no value under the key; that is why its type is string | null.
- A is wrong:
getItemknows nothing about numbers, and it never makes up a value. - B is wrong: an empty string is a real saved value, which
setItem("score", "")would create. A missing key is different, andnullsays so. - D is wrong: asking for a missing key is normal (it happens on every first visit), so it does not throw.
Reread 21.1 Saving Data in localStorage if you chose differently.
Question 2 · Tracing
Earlier, someone saved the name Sam on this page. Now greeting.dom.ts runs again, and the user types Lee (with spaces) and submits the form. What does the console show, and what does the greeting say at the end? What does the next reload say?
Check your reasoning
Sam
Lee- Line 8 finds
"Sam"under"name", line 9 logs it, and line 13 showsWelcome back, Sam!. - On submit, line 18 trims the spaces, so
nameis"Lee". Line 19’ssetItemreplacesSam, because a key holds one value. Line 21 reads backLee. - The greeting ends as
Nice to meet you, Lee!, and the next reload saysWelcome back, Lee!.
Reread 21.1 Saving Data in localStorage if your answer differed.
21.2 Storage Holds Only Strings
The notebook has one strict rule: every value is a string. That is fine for a name. It is a problem for a game’s coin count, a high score, or a “dark mode is on” flag, because the program wants a number or a boolean. You already have the tools from Day 2: String() turns a value into a string before saving, and Number() turns the saved string back into a number after loading.
The checker enforces the rule on the way in. setItem’s type says its value parameter is a string, so passing a number is a type error, not a silent conversion:
const coins = 25;
localStorage.setItem("coins", coins);set-number.ts:2:31 - error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'.
Column 31 is coins. The fix is to convert it yourself: localStorage.setItem("coins", String(coins)). Fix or delete this file before you go on.
Worked example: A coin counter that survives reloads
The page shows a count and two buttons:
<p>Coins: <span id="coins"></span></p>
<button id="earn" type="button">Earn 5 coins</button>
<button id="reset" type="button">Reset</button>const coinsText = document.querySelector<HTMLSpanElement>("#coins");
const earnButton = document.querySelector<HTMLButtonElement>("#earn");
const resetButton = document.querySelector<HTMLButtonElement>("#reset");
if (coinsText === null || earnButton === null || resetButton === null) {
throw new Error("The page is missing an element");
}
let coins = Number(localStorage.getItem("coins") ?? "0");
coinsText.textContent = String(coins);
console.log(coins);
earnButton.addEventListener("click", () => {
coins = coins + 5;
localStorage.setItem("coins", String(coins));
coinsText.textContent = String(coins);
console.log(localStorage.getItem("coins"));
});
resetButton.addEventListener("click", () => {
coins = 0;
localStorage.removeItem("coins");
coinsText.textContent = String(coins);
console.log(localStorage.getItem("coins"));
});To try it the way this trace does, type localStorage.setItem("coins", "20") in the Console tab first, as if you had played earlier, and reload. Then click Earn 5 coins twice and Reset once.
| Step | Line(s) | coins |
Saved under "coins" |
Console |
|---|---|---|---|---|
| Page loads | 8 | 20 | "20" |
20 |
| Click Earn | 13–16 | 25 | "25" |
25 |
| Click Earn | 13–16 | 30 | "30" |
30 |
| Click Reset | 20–23 | 0 | (no key) | null |
Line 8 does three things, innermost first. getItem("coins") gives "20", a string | null. The ?? from Day 9 replaces null with "0", so a first visit counts from zero and the result is now a plain string. Number() turns "20" into 20. On the way out, line 14 does the reverse with String(coins). Line 21 uses removeItem instead of saving "0": after a reset there is nothing left to remember, so getItem on line 23 gives null, and the next visit takes the ?? "0" path on line 8, which shows 0. The console shows:
20
25
30
nullWatch out
Forgetting Number() when loading. The checker cannot catch this one, because joining a string and a number with + is legal (Day 3):
const coinsText = document.querySelector<HTMLParagraphElement>("#coins");
if (coinsText === null) {
throw new Error("The page is missing #coins");
}
const saved = localStorage.getItem("coins") ?? "0";
const coins = saved + 5;
coinsText.textContent = `Coins: ${coins}`;
console.log(typeof coins);With "20" saved, the paragraph says Coins: 205, and the console shows:
stringsaved is the string "20", so line 7 joins "20" and 5 into "205" instead of adding. The type of coins is string, which is legal everywhere a template literal is used, so npx tsc reports nothing. The symptom is wrong numbers on the page, not an error. The fix is Number(saved) + 5. When a stored number looks like two numbers glued together, look for a missing Number().
Key idea
localStorage stores strings only. Convert with String() before setItem (the checker insists), and with
Number() after getItem (the checker cannot remind you). removeItem deletes a key so the next getItem gives
null.
Pause and try
Question 3 · Tracing
"3" is saved under the key "level". Predict exactly what the console shows.
const level = localStorage.getItem("level") ?? "1";
console.log(level + 1);
console.log(Number(level) + 1);
localStorage.setItem("level", String(Number(level) * 2));
console.log(localStorage.getItem("level"));
localStorage.removeItem("level");
console.log(localStorage.getItem("level") ?? "gone");Check your reasoning
31
4
6
gone- Line 1:
getItemgives"3", so the?? "1"default is not used andlevelis the string"3". - Line 2: string plus number joins:
"31". - Line 3:
Number("3") + 1adds:4. - Line 5:
Number("3") * 2is6;String()makes it"6", which replaces"3". Line 6 shows6. - Line 8 deletes the key, so on line 9
getItemgivesnulland??swaps in"gone".
Reread 21.2 Storage Holds Only Strings if any line differed.
Question 4 · Debugging
npx tsc rejects set-number.ts with TS2345. Explain what the message means, write the corrected line 2, and say what is saved when it runs.
Check your reasoning
The message says the second argument of setItem must be a string, and coins is a number. Storage keeps strings only, so TypeScript refuses to let you pretend otherwise. Convert first:
localStorage.setItem("coins", String(coins));This saves the string "25" under "coins". Loading it later needs Number() again, as line 8 of coins.dom.ts shows. (`${coins}` would also give "25".)
Reread 21.2 Storage Holds Only Strings if your fix differed.
21.3 Saving Arrays and Objects with JSON.stringify
A shopping list is an array of strings. A task is an object with a title and a done flag. Neither is a string, and the checker says so:
const shopping = ["milk", "eggs", "bread"];
localStorage.setItem("shopping", shopping);set-array.ts:2:34 - error TS2345: Argument of type 'string[]' is not assignable to parameter of type 'string'.
Fix or delete this file before you go on. The tempting fix is the one that worked for numbers in 21.2: wrap the value in String(). Watch what that actually saves:
const shopping = ["milk", "eggs", "bread"];
const settings = { theme: "dark", fontSize: 18 };
localStorage.setItem("shopping", String(shopping));
localStorage.setItem("settings", String(settings));
console.log(localStorage.getItem("shopping"));
console.log(localStorage.getItem("settings"));milk,eggs,bread
[object Object]
The checker is satisfied, because String() always gives a string. But the data is damaged. The array became milk,eggs,bread: you could split it on commas, until an item like salt, pepper contains a comma itself. The object is far worse: String() of any object is the text [object Object], and the theme and font size are gone for good. Nothing can load them back, because they were never saved.
What you need is a way to write an array or an object as text that keeps its whole structure, so it can be rebuilt exactly. That text format already exists. On Day 16 you met JSON (JavaScript Object Notation), the text format for data that JSON.parse reads: it looks like a JavaScript literal, but keys and strings must use double quotes. The opposite direction is JSON.stringify(value): it takes a value and gives back its JSON text, which is a string the checker accepts. Turning a value into text like this is called serializing it.
Worked example: Saving a list and a settings object
const shopping = ["milk", "eggs", "bread"];
const settings = { theme: "dark", fontSize: 18 };
localStorage.setItem("shopping", JSON.stringify(shopping));
localStorage.setItem("settings", JSON.stringify(settings));
console.log(localStorage.getItem("shopping"));
console.log(localStorage.getItem("settings"));This page shows nothing; the console shows:
["milk","eggs","bread"]
{"theme":"dark","fontSize":18}- Line 4:
JSON.stringify(shopping)gives the text["milk","eggs","bread"]: square brackets for the array, every string in double quotes, commas between, no spaces. That text is whatsetItemsaves. - Line 5: the object becomes
{"theme":"dark","fontSize":18}. Each property is written as"key":value. The string"dark"keeps its quotes; the number18does not, so JSON still records that one is text and the other a number. - Lines 7 and 8 read the saved strings back and print them exactly as stored.
Compare the two ways of turning data into a string side by side:
| Value | String(value) |
JSON.stringify(value) |
|---|---|---|
["milk", "eggs"] |
milk,eggs |
["milk","eggs"] |
{ theme: "dark", fontSize: 18 } |
[object Object] |
{"theme":"dark","fontSize":18} |
18 |
18 |
18 |
"hi" |
hi |
"hi" (with the quotes) |
For a single number, either works. For an array or an object, only JSON.stringify keeps enough to rebuild it, which is why every save from now on uses it. (JSON has no way to write a Map, a Set, a function, or undefined; keep saved data to strings, numbers, booleans, null, arrays, and plain objects.)
Key idea
To save an array or an object, store JSON.stringify(value): JSON text that keeps the whole structure. String()
passes the checker but loses data, and turns any object into [object Object].
Pause and try
Question 5 · Tracing
Predict exactly what this program shows.
const task = { title: "Read", done: false };
const scores = [90, 85];
console.log(JSON.stringify(task));
console.log(String(task));
console.log(JSON.stringify(scores));
console.log(JSON.stringify("hi"));
console.log(JSON.stringify(task).length);Check your reasoning
{"title":"Read","done":false}
[object Object]
[90,85]
"hi"
29- Line 4: the object as JSON.
falsehas no quotes, because it is a boolean, not text. - Line 5:
String()of any object is[object Object]. - Line 6: an array of numbers, no spaces, no quotes.
- Line 7: a string serialized as JSON keeps its double quotes, so it shows
"hi". - Line 8:
JSON.stringifygives an ordinary string, so it has alength: count the characters of{"title":"Read","done":false}and you get 29.
Reread 21.3 Saving Arrays and Objects with JSON.stringify if any line differed.
Question 6 · Multiple choice
const tasks = [{ title: "Read", done: false }]; Which line saves tasks so that it can be loaded back exactly?
localStorage.setItem("tasks", tasks);localStorage.setItem("tasks", String(tasks));localStorage.setItem("tasks", JSON.stringify(tasks));localStorage.setItem(JSON.stringify(tasks), "tasks");
Check your reasoning
C. JSON.stringify writes the array and its objects as JSON text, which JSON.parse can turn back into the same data.
- A is wrong: the checker rejects it with TS2345, because the value must be a
string. - B is wrong: it passes the checker but saves
[object Object], so the task is lost. - D is wrong: the arguments are swapped. It saves the word
tasksunder a very long key, andgetItem("tasks")would still givenull.
Reread 21.3 Saving Arrays and Objects with JSON.stringify if you chose differently.
21.4 Loading with JSON.parse into unknown
Loading is the reverse trip: getItem gives the JSON text, and JSON.parse rebuilds the value from it. Here is the round trip in one program (no page or storage needed, so run it with node src/parse-round-trip.ts):
const saved = JSON.stringify(["milk", "eggs"]);
console.log(saved);
console.log(typeof saved);
const loaded: unknown = JSON.parse(saved);
console.log(loaded);
console.log(Array.isArray(loaded));["milk","eggs"]
string
[ 'milk', 'eggs' ]
true
Line 3 confirms that the saved form is just a string. Line 6 shows that JSON.parse gave back a real array again (Node prints arrays with spaces and single quotes; that is only how it displays them). Line 7’s Array.isArray(value) asks “is this an array?” and gives a boolean.
Now the important part, which Day 16 taught: JSON.parse is typed to return any, the type that switches the checker off. That made sense for the people who wrote it: they cannot know what text you will pass in. But on a page, the text comes from storage, and you do not control what is in storage. You saved it last week with an older version of your app; or a user (or you, testing) edited it in the Application tab; or a different part of the site used the same key for something else. Watch what any lets through when the saved text is an object but the code expects an array:
const saved = '{"item":"milk"}';
const shopping = JSON.parse(saved);
for (const item of shopping) {
console.log(item.toUpperCase());
}npx tsc reports nothing, and node src/parse-any.ts crashes:
TypeError: shopping is not iterable
The checker could not help, because shopping is any: every use of it is allowed, including for...of over something that is not an array and toUpperCase on something that might not be a string. The crash happens on the user’s screen, not in your terminal.
The fix from Day 16 is one annotation: store the result as unknown. unknown is the honest type for “some value, I have not checked what”: it accepts anything when you store it, but allows nothing to be done with it until you narrow it.
const saved = '{"item":"milk"}';
const shopping: unknown = JSON.parse(saved);
for (const item of shopping) {
console.log(item.toUpperCase());
}parse-unknown.ts:3:20 - error TS18046: 'shopping' is of type 'unknown'.
Same code, one annotation added on line 2, and the checker now stops the loop before it can crash. TS18046 is the checker saying “check what this is first”. Fix or delete this file before you go on; 21.5 shows the check.
There is a second way loading can fail, and unknown does not help with it. If the saved text is not valid JSON at all, perhaps cut off halfway or typed by hand, JSON.parse itself throws before it returns anything:
const saved = '["milk","eg';
const shopping: unknown = JSON.parse(saved);
console.log(shopping);SyntaxError: Unterminated string in JSON at position 11 (line 1 column 12)
The text ["milk","eg stops in the middle of a string, so there is no value to build. A SyntaxError is a runtime error, so the checker cannot see it coming: it type-checks clean. You already know the defence from Day 16: try and catch.
Key idea
Loading is JSON.parse(getItem(key)). Annotate the result as unknown, because storage can hold anything; the
checker then refuses every use until you check the value. Text that is not valid JSON makes JSON.parse throw a
SyntaxError, so loading also needs try and catch.
Pause and try
Question 7 · Tracing
Predict exactly what this program shows. Each string in the array is a piece of JSON text.
const values = ["42", '"42"', "true", "[1, 2]", '{"a": 1}', "null"];
for (const text of values) {
const parsed: unknown = JSON.parse(text);
console.log(typeof parsed);
}Check your reasoning
number
string
boolean
object
object
objectJSON.parse builds a value of whatever type the text describes, which is exactly why its result must be treated as unknown.
42is a number;"42"with double quotes is a string;trueis a boolean.- An array and an object are both
"object"to Day 2’stypeof; that is whyArray.isArrayexists. nullis valid JSON, andtypeof nullis"object"too, a long-standing JavaScript quirk. A check for “is an object” must therefore also check!== null, which 21.6 does.
Reread 21.4 Loading with JSON.parse into unknown if any line differed.
Question 8 · Multiple choice
Why does a program that loads from storage write const data: unknown = JSON.parse(saved); instead of letting data be any?
- Because
unknownmakesJSON.parsecheck the data at run time - Because with
unknown, the checker rejects every use ofdatauntil the code has checked what it really is - Because
anyvalues cannot be stored in a variable - Because
unknownstopsJSON.parsefrom throwing on broken text
Check your reasoning
B. unknown is a promise to yourself: nothing is assumed about the value, so the checker forces a check before any use.
- A is wrong: types are erased before the program runs. The annotation changes what the checker allows, not what
JSON.parsedoes. - C is wrong: an
anyvalue can go anywhere. That is the problem: it switches the checker off. - D is wrong: broken JSON throws a
SyntaxErrorwhatever the annotation says; onlytryandcatchhandle that.
Reread 21.4 Loading with JSON.parse into unknown if you chose differently.
21.5 Validating and Falling Back to Defaults
Loading can now go wrong in three distinct ways, and a well-built page survives all three:
| What is in storage | Example | What getItem + JSON.parse do |
|---|---|---|
| Missing: never saved | (no key) | getItem gives null |
| Corrupted: not valid JSON | ["milk","eg |
JSON.parse throws a SyntaxError |
| Wrong shape: valid, but not what you expect | {"item":"milk"} |
parses fine, into the wrong kind of value |
For each, the page should not crash and should not show nonsense. It should fall back to a default: carry on with a sensible starting value, usually an empty list, as if this were a first visit. That is the same idea as the ?? "0" in 21.2, grown up to handle objects.
The third row needs a type guard, which you wrote on Day 16: a function whose return type is value is SomeType. It returns a boolean, and when it returns true, the checker narrows the value to that type. For a shopping list, the question is “is this an array, and is every element a string?”:
Worked example: A loader that never crashes
This program has no page: loadList takes the text that getItem would give, so you can test all three failures from the terminal with node src/load-list.ts.
function isStringArray(value: unknown): value is string[] {
return (
Array.isArray(value) && value.every((item) => typeof item === "string")
);
}
function loadList(saved: string | null): string[] {
if (saved === null) {
return [];
}
try {
const data: unknown = JSON.parse(saved);
return isStringArray(data) ? data : [];
} catch {
return [];
}
}
console.log(loadList(null));
console.log(loadList('["milk","eggs"]'));
console.log(loadList('["milk","eg'));
console.log(loadList('{"item":"milk"}'));
console.log(loadList('["milk",42]'));[]
[ 'milk', 'eggs' ]
[]
[]
[]| Lines | What happens |
|---|---|
| 1–5 | The type guard: Array.isArray first, then Day 11’s every asks whether each element’s typeof is "string" |
| 8–10 | Missing: null means nothing was saved, so return the default, an empty list |
| 11–12 | Parse into unknown, inside try |
| 13 | Wrong shape or right shape: if the guard says yes, data is narrowed to string[] and returned; otherwise the default |
| 14–15 | Corrupted: JSON.parse threw, so control jumps here and the default is returned |
Now each call at the bottom:
nullis missing, so line 9 returns[].["milk","eggs"]parses into an array of strings; the guard says yes, and the real list comes back.["milk","egmakesJSON.parsethrow; line 15 returns[].{"item":"milk"}parses into an object, not an array; the guard says no.["milk",42]is an array, buteveryfinds a number; the guard says no.
Two details on lines 13 and 14. On line 13, isStringArray(data) ? data : [] is Day 4’s conditional operator, and it type-checks only because the guard narrows data from unknown to string[] in the “yes” branch. And line 14 is Day 16’s catch { with no name for the error: here any failure means the same thing, that the saved text is unusable, so the code does not need to look at what was thrown.
Here is the loader on a page. To try it, type localStorage.setItem("shopping", '["milk","eg') in the console to corrupt the list on purpose, then reload:
<h1>Shopping list</h1>
<p id="message"></p>
<ul id="shopping"></ul>function isStringArray(value: unknown): value is string[] {
return (
Array.isArray(value) && value.every((item) => typeof item === "string")
);
}
function loadList(saved: string | null): string[] {
if (saved === null) {
return [];
}
try {
const data: unknown = JSON.parse(saved);
return isStringArray(data) ? data : [];
} catch {
return [];
}
}
const list = document.querySelector<HTMLUListElement>("#shopping");
const message = document.querySelector<HTMLParagraphElement>("#message");
if (list === null || message === null) {
throw new Error("The page is missing an element");
}
const shopping = loadList(localStorage.getItem("shopping"));
if (shopping.length === 0) {
message.textContent = "Nothing on your list yet.";
}
for (const item of shopping) {
const listItem = document.createElement("li");
listItem.textContent = item;
list.append(listItem);
}The page does not crash. loadList returns [], so line 27 shows Nothing on your list yet. and the loop on lines 29 to 33 adds no items:
<h1>Shopping list</h1>
<p id="message">Nothing on your list yet.</p>
<ul id="shopping"></ul>
Change the saved value to '["milk","eggs"]' and reload: the message stays empty and two <li> items appear. Same script, three kinds of storage, and no crash in any of them.
Watch out
Using as instead of a check. Day 16 warned that a type assertion only tells the checker what to believe; it checks nothing. With saved data, it hides exactly the bug you are trying to catch. Suppose an older version of your app saved tasks with a name property, and the new version calls it title:
type Task = { title: string; done: boolean };
const saved = '[{"name":"Water the plants","done":false}]';
const tasks = JSON.parse(saved) as Task[];
for (const task of tasks) {
console.log(task.title.toUpperCase());
}npx tsc is happy, because line 4 claims the data is Task[]. At run time, task.title is undefined, and line 6 crashes:
TypeError: Cannot read properties of undefined (reading 'toUpperCase')Replace the as with unknown and a type guard, as load-list.ts does, and the same old data quietly becomes the default instead.
Key idea
Loading is safe only when all three failures fall back to a default: null (nothing saved), a throw from JSON.parse
(corrupted), and a type guard that says no (wrong shape). A type assertion with as checks none of them.
Pause and try
Question 9 · Tracing
Lines 1 to 17 of predict-load.ts are the same two functions as in load-list.ts. Predict exactly what lines 19 to 22 show.
function isStringArray(value: unknown): value is string[] {
return (
Array.isArray(value) && value.every((item) => typeof item === "string")
);
}
function loadList(saved: string | null): string[] {
if (saved === null) {
return [];
}
try {
const data: unknown = JSON.parse(saved);
return isStringArray(data) ? data : [];
} catch {
return [];
}
}
console.log(loadList("[]"));
console.log(loadList('"milk"'));
console.log(loadList(""));
console.log(loadList('["tea"]').length);Check your reasoning
[]
[]
[]
1- Line 19:
[]is valid JSON for an empty array, and every element of an empty array is a string (Day 11:everyon an empty array istrue). So the guard says yes, and the real, empty list comes back. It looks the same as the default, but it is the saved value. - Line 20:
"milk"is valid JSON for a string, not an array, so the guard says no. - Line 21: an empty string is not valid JSON, so
JSON.parsethrows andcatchreturns[]. - Line 22:
["tea"]loads as a one-item list, and itslengthis 1.
Reread 21.5 Validating and Falling Back to Defaults if any line differed.
Question 10 · Short answer
A classmate replaces lines 11 to 16 of load-list.ts with return JSON.parse(saved) as string[]; and says, “It type-checks, so it is safe.” Give two kinds of saved value that break their version, and say what happens with each.
Check your reasoning
A model answer:
- Corrupted text, such as
["milk","eg: with notryandcatch,JSON.parsethrows aSyntaxErrorand the page script stops. Nothing after it runs. - Wrong shape, such as
{"item":"milk"}: theastells the checker it is astring[]without checking, so the function returns an object. The crash comes later, wherever the list is used:for...offails withTypeError: … is not iterable.
A correct answer names a corrupted value and a wrong-shape value, and explains that type-checking proves nothing about data that arrives while the program runs; as turns the checker off for that value.
Reread 21.5 Validating and Falling Back to Defaults if your answer differed.
21.6 A Small Typed Storage Module
Look at what a page needs to load a list: a key string, a type guard, getItem, try, JSON.parse, two fallbacks. To save: the same key string and JSON.stringify. If that code is scattered through the event listeners, three things go wrong. A typo in the key in one place ("task" instead of "tasks") saves to one key and loads from another, and nothing reports it. One listener forgets JSON.stringify. And when the shape of a task changes, you have to find every place that touches storage.
The cure is the one Day 13 taught for any group of related code: put it in one module, a file of its own, and give the rest of the program a tiny, typed way in. Here the way in is two functions:
loadTasks(): Task[]always gives back a valid task list, nevernull, never a crash.saveTasks(tasks: Task[]): voidsaves the list.
Everything else, the key, the guard, the JSON, the fallbacks, stays hidden inside. The rest of the page only ever thinks in Task[].
Worked example: Tasks that stay done
The page is a heading and an empty list:
<h1>Tasks</h1>
<ul id="tasks"></ul>Lines 1 to 31 are the storage code; lines 33 to 63 are the page:
type Task = { title: string; done: boolean };
const tasksKey = "tasks";
function isTask(value: unknown): value is Task {
return (
typeof value === "object" &&
value !== null &&
"title" in value &&
typeof value.title === "string" &&
"done" in value &&
typeof value.done === "boolean"
);
}
function loadTasks(): Task[] {
const saved = localStorage.getItem(tasksKey);
if (saved === null) {
return [];
}
try {
const data: unknown = JSON.parse(saved);
return Array.isArray(data) && data.every(isTask) ? data : [];
} catch {
return [];
}
}
function saveTasks(tasks: Task[]): void {
localStorage.setItem(tasksKey, JSON.stringify(tasks));
}
const list = document.querySelector<HTMLUListElement>("#tasks");
if (list === null) {
throw new Error("The page is missing #tasks");
}
const tasks = loadTasks();
const render = (): void => {
list.textContent = "";
for (const task of tasks) {
const item = document.createElement("li");
const title = document.createElement("span");
title.textContent = task.title;
const button = document.createElement("button");
button.type = "button";
button.textContent = task.done ? "Undo" : "Done";
button.addEventListener("click", () => {
task.done = !task.done;
saveTasks(tasks);
console.log(localStorage.getItem(tasksKey));
render();
});
if (task.done) {
item.classList.add("done");
}
item.append(title, button);
list.append(item);
}
};
render();The storage code:
| Lines | What it does |
|---|---|
| 1 | The Task type from Day 7 |
| 3 | The key, written once, in a constant |
| 5–14 | A type guard for one task: an object (line 7), not null (line 8, since typeof null is "object"), with a string title and a boolean done. Day 9’s in narrows value so that value.title can be read |
| 16–27 | loadTasks: the three fallbacks from 21.5. On line 23, data.every(isTask) passes the guard itself to every (Day 10), so the checker learns that every element is a Task |
| 29–31 | saveTasks: serialize and save under the one key |
The page code is Day 19’s state-and-render pattern, with one addition: whenever the state changes, it is saved. To try it, first type this in the console and reload, to stand in for an earlier visit:
localStorage.setItem("tasks", '[{"title":"Water the plants","done":false},{"title":"Call Grandma","done":false}]')Line 38 loads both tasks. render empties the list (line 41) and builds one <li> per task, each with a Done button. Clicking the second task’s button runs lines 50 to 53: flip done, save the whole list, show what is now stored, and render again. The console shows:
[{"title":"Water the plants","done":false},{"title":"Call Grandma","done":true}]and the list becomes:
<ul id="tasks">
<li><span>Water the plants</span><button type="button">Done</button></li>
<li class="done"><span>Call Grandma</span><button type="button">Undo</button></li>
</ul>Reload, and Call Grandma is still done, because line 38 loads what line 51 saved.
render is Day 19’s const render = (): void => { … }, not a function declaration, for the reason Day 19 gave: only then does the checker carry line 34’s null check for list into its body.
In your Vite project, the storage code becomes its own module. Create src/storage.ts with lines 1 to 31, and put export in front of the three things the page needs:
export type Task = { title: string; done: boolean };
const tasksKey = "tasks";
function isTask(value: unknown): value is Task {
// lines 6 to 13 as before
}
export function loadTasks(): Task[] {
// lines 17 to 26 as before
}
export function saveTasks(tasks: Task[]): void {
localStorage.setItem(tasksKey, JSON.stringify(tasks));
}
Then src/main.ts keeps lines 33 to 63 and starts with Day 13’s import, with the .ts extension:
import { loadTasks, saveTasks } from "./storage.ts";
Delete line 52 (the console.log) when you move the code: tasksKey is not exported, so main.ts can no longer see the key at all. That is the point. The only way the page can touch saved tasks is through loadTasks and saveTasks, so every save is serialized the same way, every load is checked, and renaming the key means changing one line.
Watch out
Changing the state but forgetting to save. If a click handler changes tasks and calls render() but not saveTasks(tasks), the page looks right, so you will not notice until the next reload brings the old list back. A good habit: every place that changes the state saves it, right before it renders. In tasks.dom.ts that pair is lines 51 and 53.
Key idea
Keep every use of localStorage in one module with a tiny typed interface such as loadTasks(): Task[] and
saveTasks(tasks: Task[]): void. The rest of the app works only with typed data, and the key, JSON, and checks live
in one place.
Pause and try
Question 11 · Short answer
You decide to save tasks under the key "tasks-v2" instead of "tasks". With the storage module, how many lines change, and why? What would it have cost if getItem("tasks") and setItem("tasks", …) were written out in each event listener?
Check your reasoning
One line: line 3, const tasksKey = "tasks-v2";. Every load and save uses the constant, and nothing outside the module knows the key.
With the key written out in each listener, you would have to find and change every copy. Missing one is the dangerous case: that listener would save to the old key while the page loads from the new one, so some changes would silently vanish on reload, with no error from the checker or the browser. (Either way, data saved under the old key is not loaded any more; it is still in storage under "tasks".)
Reread 21.6 A Small Typed Storage Module if your answer differed.
Question 12 · Debugging
A student’s task page has an Add form. Adding a task works, and the new task appears at once, but after a reload it is gone, while tasks marked done stay done. Their submit listener ends with tasks.push({ title, done: false }); render();. What is wrong, how could you confirm it without reading more code, and what is the fix?
Check your reasoning
The submit listener changes the state but never saves it. The page shows the new task because render() draws from the tasks array in memory, but storage still holds the old list, and the reload loads that. Marking done works because the click handler does call saveTasks.
To confirm: add a task, then look at the tasks row in the Application tab (or type localStorage.getItem("tasks") in the console). The new task is not there.
The fix is to save between the change and the render:
tasks.push({ title, done: false });
saveTasks(tasks);
render();Reread 21.6 A Small Typed Storage Module if your answer differed.
21.7 Fetching a Starter File from public
On a first visit, an empty list is a correct fallback, but not always a friendly one. A shopping list could start with the staples most people buy; a flashcard app could start with a sample deck. That starting data is too long to type into the code, and you might want to change it without touching TypeScript. So it goes in a JSON file that the page fetches.
In a Vite project, the place for such a file is the public folder at the top of the project (next to index.html; create it if it is not there). Vite serves every file in public exactly as it is, at the root of the site: public/staples.json is fetched as /staples.json, without public in the address. Create public/staples.json with:
["milk", "bread", "eggs"]
You fetch it with Day 17’s tools: await fetch(url), a check of response.ok, then await response.json(). Recall that a missing file does not make fetch reject: the server answers with the status code 404 (“not found”), so response.ok is false and the code has to notice that itself. And the parsed body is untrusted, just like storage, so it goes into unknown and through the guard.
Worked example: Starter items on a first visit
The page is shopping.html from 21.5 again. Lines 1 to 17 are the two functions from load-list.ts:
function isStringArray(value: unknown): value is string[] {
return (
Array.isArray(value) && value.every((item) => typeof item === "string")
);
}
function loadList(saved: string | null): string[] {
if (saved === null) {
return [];
}
try {
const data: unknown = JSON.parse(saved);
return isStringArray(data) ? data : [];
} catch {
return [];
}
}
async function loadStaples(): Promise<string[]> {
try {
const response = await fetch("/staples.json");
if (!response.ok) {
console.log(`Could not load the starter list (${response.status})`);
return [];
}
const data: unknown = await response.json();
return isStringArray(data) ? data : [];
} catch {
return [];
}
}
const list = document.querySelector<HTMLUListElement>("#shopping");
const message = document.querySelector<HTMLParagraphElement>("#message");
if (list === null || message === null) {
throw new Error("The page is missing an element");
}
const saved = localStorage.getItem("shopping");
let shopping: string[];
if (saved === null) {
console.log("Nothing saved: loading the starter list");
shopping = await loadStaples();
} else {
console.log("Loading your saved list");
shopping = loadList(saved);
}
if (shopping.length === 0) {
message.textContent = "Nothing on your list yet.";
}
for (const item of shopping) {
const listItem = document.createElement("li");
listItem.textContent = item;
list.append(listItem);
}Run it after localStorage.clear(), as a first visit:
| Lines | What happens |
|---|---|
| 39 | getItem gives null: nothing has ever been saved |
| 41–43 | So the page logs a message and awaits loadStaples() (top-level await, from Day 17) |
| 21 | fetch("/staples.json") asks Vite for the file in public |
| 22 | The status is 200, so response.ok is true and the if is skipped |
| 26–27 | response.json() parses the body into unknown; the guard says it is a string[], so it is returned |
| 49–56 | Three items are rendered; the message stays empty |
The console shows:
Nothing saved: loading the starter listand the list shows milk, bread, and eggs.
Now vary the storage. Type localStorage.setItem("shopping", "[]") and reload. This time line 39 gets the string "[]", which is not null, so line 45 runs instead and nothing is fetched. loadList("[]") gives an empty list, and the page says Nothing on your list yet. The console shows:
Loading your saved list
That difference is deliberate. null means “this browser has never saved a list”, the one time a starter list makes sense. "[]" means “the user saved an empty list”, perhaps after buying everything. Refilling it with milk, bread, and eggs on every reload would undo what they did. Checking === null, not shopping.length === 0, is what keeps the two cases apart.
Finally, misspell the file name: change line 21 to fetch("/staple.json"), clear storage, and reload. The server has no such file and answers 404, so line 22 catches it, and the console shows:
Nothing saved: loading the starter list
Could not load the starter list (404)
The page still works: loadStaples returns [] and the page says Nothing on your list yet. The try and catch around the fetch handle the remaining failures: no network, or a file that is not valid JSON.
Watch out
Writing public in the address. fetch("/public/staples.json") looks reasonable, because that is where the file is on disk, but the site serves the folder’s contents at /. When you build the site for others, the address with public in it does not exist and gives a 404. Put the file in public/, and fetch it as /staples.json.
Key idea
Files in a Vite project’s public folder are served at the site root: public/staples.json is fetched as
/staples.json. Fetch starter data only when getItem gives null, check response.ok, and validate the JSON with
a type guard like any other untrusted data.
Pause and try
Question 13 · Tracing
["tea"] is saved under "shopping", and public/staples.json holds ["milk", "bread", "eggs"]. staples.dom.ts runs. What does the console show, is /staples.json fetched, and which items appear?
Check your reasoning
Loading your saved listgetItem on line 39 gives '["tea"]', not null, so the else branch on lines 44 to 46 runs. loadStaples is never called, so nothing is fetched. loadList parses and checks the saved text and gives ["tea"], so the page shows one item, tea, and an empty message. The starter list only matters on a first visit.
Reread 21.7 Fetching a Starter File from public if your answer differed.
Question 14 · Multiple choice
A Vite project needs a starter deck of flashcards on first visit. Where does the file go, and what does the page fetch?
src/deck.json, fetched withfetch("/src/deck.json")public/deck.json, fetched withfetch("/public/deck.json")public/deck.json, fetched withfetch("/deck.json")- In
localStorageunder the key"deck", fetched withfetch("deck")
Check your reasoning
C. Vite serves the contents of public/ at the root of the site, unchanged, so public/deck.json has the address /deck.json.
- A is wrong:
src/holds the code Vite builds; it is not a folder of files served as they are. - B is wrong: the folder’s name is not part of the address; this request gives a 404 when the site is built.
- D is wrong:
fetchasks the server for a file over the network; it never readslocalStorage. The starter file is what you use when storage is empty.
Reread 21.7 Fetching a Starter File from public if you chose differently.
21.8 What Not to Store in the Browser
Saving is now easy, which raises the question of what should be saved. localStorage is convenient, not secret. Three facts about it decide what belongs there:
- It is plain text on the device. Anyone who sits at the computer can open the developer tools and read every key, as you have been doing all day. It is not encrypted and has no password.
- Every script on the page can read it. Your code, and any other code the page loads, can call
getItem. If an attacker ever manages to run a script on your page, everything in storage is theirs. - It belongs to one browser on one device, and it can vanish. The user’s phone does not see what their laptop saved. Clearing browsing data deletes it. Browsers also limit each site to a few megabytes.
Those facts sort data into two groups:
Fine to keep in localStorage |
Never keep in localStorage |
|---|---|
| A theme or font-size choice | Passwords, in any form |
| A to-do list or shopping list on a personal device | Payment card numbers, bank details |
| A game’s high score, a draft the user is typing | Private information about a person: health, ID numbers, home address |
| Which tab or filter was last open | Anything another user of the same computer must not see |
The rule of thumb: store only what you would be comfortable seeing on a shared school computer, and only what the user could afford to lose. Passwords and private data belong on a server built to protect them, behind a login, which is far beyond this course. A page that never stores them cannot leak them.
Key idea
localStorage is readable by anyone at the device and by any script on the page, is limited to one browser, and can
be cleared at any time. Store preferences and personal, low-stakes data there; never passwords or private information.
Pause and try
Question 15 · Multiple choice
A study app wants to remember four things between visits. Which one should not go in localStorage?
- Whether the user chose the dark theme
- The user’s password, so they do not have to type it again
- The last flashcard deck the user opened
- The user’s best quiz score
Check your reasoning
B. Anyone at the device can read storage in the developer tools, and any script on the page can read it with getItem. A password is exactly what must never be readable like that.
- A is fine: a preference is harmless if seen and cheap to lose.
- C is fine: it is a convenience, not a secret.
- D is fine: a score is low-stakes. If it disappears, nothing bad happens.
Reread 21.8 What Not to Store in the Browser if you chose differently.
Putting it together
A shopping list app that remembers everything: on a first visit it starts from the staples file, and from then on it loads the saved list. You add items with a form and remove them with buttons, and every change is saved. It uses every idea from today. The page:
<h1>Shopping list</h1>
<form id="add-form">
<label for="item">Item</label>
<input id="item" name="item">
<button>Add</button>
</form>
<p id="status" aria-live="polite"></p>
<ul id="shopping"></ul>Keep public/staples.json from 21.7, clear storage, and put the script in src/main.ts:
function isStringArray(value: unknown): value is string[] {
return (
Array.isArray(value) && value.every((item) => typeof item === "string")
);
}
function loadList(saved: string | null): string[] {
if (saved === null) {
return [];
}
try {
const data: unknown = JSON.parse(saved);
return isStringArray(data) ? data : [];
} catch {
return [];
}
}
async function loadStaples(): Promise<string[]> {
try {
const response = await fetch("/staples.json");
if (!response.ok) {
return [];
}
const data: unknown = await response.json();
return isStringArray(data) ? data : [];
} catch {
return [];
}
}
const shoppingKey = "shopping";
function saveList(items: string[]): void {
localStorage.setItem(shoppingKey, JSON.stringify(items));
console.log(localStorage.getItem(shoppingKey));
}
const form = document.querySelector<HTMLFormElement>("#add-form");
const input = document.querySelector<HTMLInputElement>("#item");
const status = document.querySelector<HTMLParagraphElement>("#status");
const list = document.querySelector<HTMLUListElement>("#shopping");
if (form === null || input === null || status === null || list === null) {
throw new Error("The page is missing an element");
}
const saved = localStorage.getItem(shoppingKey);
const shopping = saved === null ? await loadStaples() : loadList(saved);
const render = (): void => {
list.textContent = "";
for (const [index, item] of shopping.entries()) {
const listItem = document.createElement("li");
const name = document.createElement("span");
name.textContent = item;
const removeButton = document.createElement("button");
removeButton.type = "button";
removeButton.textContent = "Remove";
removeButton.addEventListener("click", () => {
shopping.splice(index, 1);
saveList(shopping);
status.textContent = `Removed ${item}.`;
render();
});
listItem.append(name, removeButton);
list.append(listItem);
}
};
form.addEventListener("submit", (event) => {
event.preventDefault();
const item = input.value.trim();
if (item === "") {
status.textContent = "Type an item first.";
return;
}
shopping.push(item);
saveList(shopping);
input.value = "";
status.textContent = `Added ${item}.`;
render();
});
render();Type apples, press Add, and then press the Remove button next to bread. The console shows the saved text after each change:
["milk","bread","eggs","apples"]
["milk","eggs","apples"]
and the page ends as:
<p id="status" aria-live="polite">Removed bread.</p>
<ul id="shopping">
<li><span>milk</span><button type="button">Remove</button></li>
<li><span>eggs</span><button type="button">Remove</button></li>
<li><span>apples</span><button type="button">Remove</button></li>
</ul>
Follow the data through the program:
| Lines | What happens | Idea |
|---|---|---|
| 1–17 | The guard and the loader: a missing, corrupted, or wrong-shape list becomes [] |
21.4, 21.5 |
| 19–30 | The starter list from /staples.json, checked with response.ok and the guard |
21.7 |
| 32–37 | One key constant and one save function that serializes with JSON.stringify |
21.3, 21.6 |
| 47–48 | null means first visit, so fetch the starter list; otherwise load what was saved, even if it is [] |
21.1, 21.7 |
| 59–63 | Remove: Day 6’s splice takes the item out, then save, announce, render |
21.6 |
| 77–81 | Add: push, save, clear the input, announce, render | 21.6 |
| 74, 80 | Messages go in an aria-live paragraph (Day 20), so screen readers hear them |
Line 48 uses the conditional operator with await in one branch: if nothing is saved, the page waits for the starter file; otherwise it loads at once. Now reload. Line 47 finds the saved text, so the list comes back as milk, eggs, apples, with no fetch. Then corrupt it in the console with localStorage.setItem("shopping", "oops") and reload: the page shows an empty list instead of crashing, and the next item you add saves a fresh, valid list over the broken one.
Notice that lines 1 to 37 never touch the page, and lines 39 to 84 reach localStorage only once, on line 47, which asks whether anything is saved yet. Everything else goes through loadList and saveList. That split is where a src/storage.ts module would begin and end.
Vocabulary
| Term | Definition | Example |
|---|---|---|
| localStorage | The browser’s store of key-value pairs for one site, kept between visits | localStorage.setItem("name", "Ana") |
| key-value pair | A value saved under a name, the key, which is used to find it again | key "coins", value "20" |
| key | The name a value is saved under | "tasks" |
| value | The data saved under a key; in localStorage, always a string |
'["milk","eggs"]' |
| JSON | A text format for data that looks like JavaScript literals, with double-quoted keys and strings | {"title":"Read","done":false} |
| serializing | Turning a value into text so it can be saved and rebuilt later | JSON.stringify(tasks) |
| fall back to a default | Carry on with a sensible starting value when saved data is missing or unusable | return []; in the catch |
| module | A file of related code that exports only what the rest of the program needs | src/storage.ts exporting loadTasks, saveTasks |
| public folder | The Vite project folder whose files are served unchanged at the site root | public/staples.json → /staples.json |
Summary
localStoragekeeps key-value pairs in this browser between visits:setItem(key, value)saves,getItem(key)loads and givesnullwhen nothing is saved (typestring | null), andremoveItem(key)deletes.- Every value is a string. Convert numbers with
String()before saving (the checker insists) andNumber()after loading (the checker cannot remind you; forgetting gives"205"). Save arrays and objects as JSON withJSON.stringify, never withString(). - Load with
JSON.parseintounknown, neveranyoras. A safe loader falls back to a default in all three failure cases: missing (null), corrupted (JSON.parsethrows, so usetryandcatch), and wrong shape (a type guard says no). - Keep storage code in one typed module with functions like
loadTasks(): Task[]andsaveTasks(tasks: Task[]): void; save every time the state changes, before rendering. - Starter data goes in the public folder and is fetched from the site root (
/staples.json) only whengetItemgivesnull; checkresponse.okand validate the JSON. localStorageis readable by anyone at the device and any script on the page: never store passwords or private information.
Practice
Do these in your day21 project, with npm run dev running. First make sure npx tsc prints nothing: if any broken file from today is still in src/ (name-possibly-null.ts, set-number.ts, set-array.ts, or parse-unknown.ts), fix it or delete it. Then write each page yourself, check it with npx tsc, try it in the browser (including a reload, localStorage.clear(), and a corrupted value typed into the console), and only then open the answer.
Question 16 · Short answer
A task list that survives a reload. Take Day 20’s task list, where a form adds a task, and make it save. Each task has a title and a done flag; a button on each task toggles it. Load the saved tasks when the page opens, save after every change, and make sure a missing, corrupted, or wrong-shape saved list gives an empty list instead of a crash.
Check your reasoning
One possible solution. The page:
<h1>Tasks</h1>
<form id="task-form">
<label for="title">New task</label>
<input id="title" name="title">
<button>Add</button>
</form>
<p id="status" aria-live="polite"></p>
<ul id="tasks"></ul>type Task = { title: string; done: boolean };
const tasksKey = "tasks";
function isTask(value: unknown): value is Task {
return (
typeof value === "object" &&
value !== null &&
"title" in value &&
typeof value.title === "string" &&
"done" in value &&
typeof value.done === "boolean"
);
}
function loadTasks(): Task[] {
const saved = localStorage.getItem(tasksKey);
if (saved === null) {
return [];
}
try {
const data: unknown = JSON.parse(saved);
return Array.isArray(data) && data.every(isTask) ? data : [];
} catch {
return [];
}
}
function saveTasks(tasks: Task[]): void {
localStorage.setItem(tasksKey, JSON.stringify(tasks));
console.log(`Saved: ${localStorage.getItem(tasksKey)}`);
}
const form = document.querySelector<HTMLFormElement>("#task-form");
const input = document.querySelector<HTMLInputElement>("#title");
const status = document.querySelector<HTMLParagraphElement>("#status");
const list = document.querySelector<HTMLUListElement>("#tasks");
if (form === null || input === null || status === null || list === null) {
throw new Error("The page is missing an element");
}
const tasks = loadTasks();
const render = (): void => {
list.textContent = "";
for (const task of tasks) {
const item = document.createElement("li");
const title = document.createElement("span");
title.textContent = task.title;
const button = document.createElement("button");
button.type = "button";
button.textContent = task.done ? "Undo" : "Done";
button.addEventListener("click", () => {
task.done = !task.done;
saveTasks(tasks);
render();
});
if (task.done) {
item.classList.add("done");
}
item.append(title, button);
list.append(item);
}
};
form.addEventListener("submit", (event) => {
event.preventDefault();
const title = input.value.trim();
if (title === "") {
status.textContent = "Type a task first.";
return;
}
tasks.push({ title, done: false });
saveTasks(tasks);
input.value = "";
status.textContent = `Added "${title}".`;
render();
});
render();Lines 1 to 32 are the storage code from 21.6, with one line added to saveTasks that logs what was saved. To test it, the task Water the plants, already done, was saved first. Typing Buy milk, pressing Add, then pressing the first task’s button gives:
Saved: [{"title":"Water the plants","done":true},{"title":"Buy milk","done":false}]
Saved: [{"title":"Water the plants","done":false},{"title":"Buy milk","done":false}]The page loads with loadTasks on line 42, so a reload shows both tasks as they were left. Both places that change the state, the click handler (lines 54 to 56) and the submit listener (lines 73 to 77), save before they render, and the status paragraph announces each new task. Delete the log line in saveTasks once you trust it. Then move lines 1 to 32 into src/storage.ts as 21.6 shows.
Reread 21.6 A Small Typed Storage Module and 21.5 Validating and Falling Back to Defaults if your page lost tasks or crashed on bad data.
Question 17 · Short answer
Remember the theme. Add a button that switches the page between a light and a dark theme by putting the class light or dark on <body>. Save the choice, and apply the saved theme as soon as the page loads. A missing or nonsense saved value should give the light theme.
Check your reasoning
One possible solution. The page is a single button:
<button id="theme-button" type="button"></button>type Theme = "light" | "dark";
function isTheme(value: unknown): value is Theme {
return value === "light" || value === "dark";
}
function loadTheme(): Theme {
const saved = localStorage.getItem("theme");
return isTheme(saved) ? saved : "light";
}
const button = document.querySelector<HTMLButtonElement>("#theme-button");
if (button === null) {
throw new Error("The page is missing #theme-button");
}
let theme = loadTheme();
const applyTheme = (): void => {
document.body.classList.remove("light", "dark");
document.body.classList.add(theme);
button.textContent = theme === "dark" ? "Switch to light" : "Switch to dark";
console.log(`body class: ${document.body.className}`);
};
button.addEventListener("click", () => {
theme = theme === "dark" ? "light" : "dark";
localStorage.setItem("theme", theme);
applyTheme();
});
applyTheme();With dark saved, loading the page and clicking the button once shows:
body class: dark
body class: lightand the button ends up saying Switch to dark. The theme is a single word, so no JSON is needed: setItem("theme", theme) stores it as it is. Loading still treats it as untrusted: Day 9’s literal union Theme and the guard on lines 3 to 5 mean a missing key (null) or a value like "purple" falls back to "light" on line 9, and after that the checker knows theme is one of exactly two strings. Add CSS such as body.dark { background: #111; color: #eee; } to src/style.css to see it change.
Reread 21.5 Validating and Falling Back to Defaults and 21.1 Saving Data in localStorage if your answer differed.
Question 18 · Short answer
A starter list on the first visit. Create public/starter.json with two starter tasks. The first time the page opens (nothing saved), load the tasks from that file, save them, and show them. On every later visit, show the saved tasks instead, even if the user has emptied the list.
Check your reasoning
One possible solution. public/starter.json:
[
{ "title": "Read today's lesson", "done": false },
{ "title": "Try the practice", "done": false }
]The page is <h1>Tasks</h1> and <ul id="tasks"></ul>; lines 1 to 31 are the storage code from 21.6:
type Task = { title: string; done: boolean };
const tasksKey = "tasks";
function isTask(value: unknown): value is Task {
return (
typeof value === "object" &&
value !== null &&
"title" in value &&
typeof value.title === "string" &&
"done" in value &&
typeof value.done === "boolean"
);
}
function loadTasks(): Task[] {
const saved = localStorage.getItem(tasksKey);
if (saved === null) {
return [];
}
try {
const data: unknown = JSON.parse(saved);
return Array.isArray(data) && data.every(isTask) ? data : [];
} catch {
return [];
}
}
function saveTasks(tasks: Task[]): void {
localStorage.setItem(tasksKey, JSON.stringify(tasks));
}
async function loadStarterTasks(): Promise<Task[]> {
try {
const response = await fetch("/starter.json");
if (!response.ok) {
return [];
}
const data: unknown = await response.json();
return Array.isArray(data) && data.every(isTask) ? data : [];
} catch {
return [];
}
}
const list = document.querySelector<HTMLUListElement>("#tasks");
if (list === null) {
throw new Error("The page is missing #tasks");
}
let tasks: Task[];
if (localStorage.getItem(tasksKey) === null) {
tasks = await loadStarterTasks();
saveTasks(tasks);
console.log("First visit: saved the starter tasks");
} else {
tasks = loadTasks();
console.log("Welcome back: loaded your tasks");
}
for (const task of tasks) {
const item = document.createElement("li");
item.textContent = task.title;
if (task.done) {
item.classList.add("done");
}
list.append(item);
}
console.log(localStorage.getItem(tasksKey));On a first visit, the console shows:
First visit: saved the starter tasks
[{"title":"Read today's lesson","done":false},{"title":"Try the practice","done":false}]and both tasks are listed. Line 52 asks === null, so only a browser that has never saved tasks fetches the file; a saved [] takes the else branch. Line 54 saves the starter tasks at once, so the next visit says Welcome back: loaded your tasks and no longer depends on the file. loadStarterTasks treats the fetched JSON like storage: response.ok for a missing file, unknown and the guard for the wrong shape, and catch for anything else.
Reread 21.7 Fetching a Starter File from public if your answer differed.
Review questions
Question 19 · Tracing
Storage holds visits = "4" and name = "Sam", and nothing else. Predict exactly what the console shows.
const visits = Number(localStorage.getItem("visits") ?? "0") + 1;
localStorage.setItem("visits", String(visits));
localStorage.removeItem("name");
console.log(localStorage.getItem("visits"));
console.log(localStorage.getItem("name") ?? "no name");
console.log((localStorage.getItem("visits") ?? "") + 1);
console.log(localStorage.getItem("theme"));Check your reasoning
5
no name
51
null- Line 1:
Number("4") + 1is5. Line 2 saves it as"5". - Line 3 deletes
name. - Line 5: the saved string
5. - Line 6:
nameis gone, sogetItemgivesnulland??supplies"no name". - Line 7:
getItemgives"5"(a string), and"5" + 1joins to"51"; the missingNumber()again. - Line 8: nothing was ever saved under
"theme", sonull.
Reread 21.2 Storage Holds Only Strings if any line differed.
Question 20 · Debugging
This code should keep the best score. npx tsc reports two errors. Explain each and write a corrected version.
const best: number = localStorage.getItem("best");
const score = 120;
if (score > best) {
localStorage.setItem("best", score);
}review-score.ts:1:7 - error TS2322: Type 'string | null' is not assignable to type 'number'.
Type 'null' is not assignable to type 'number'.
review-score.ts:4:32 - error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'.Check your reasoning
- Line 1, TS2322:
getItemgivesstring | null, never a number. The indented line names the first problem the checker sees,null, but astringwould not fitnumbereither. Supply a default fornulland convert withNumber(). - Line 4, TS2345:
setItemonly takes a string, so convert withString().
A corrected version, on a page with <p id="best"></p>:
const bestText = document.querySelector<HTMLParagraphElement>("#best");
if (bestText === null) {
throw new Error("The page is missing #best");
}
let best = Number(localStorage.getItem("best") ?? "0");
const score = 120;
if (score > best) {
best = score;
localStorage.setItem("best", String(best));
}
bestText.textContent = `Best score: ${best}`;
console.log(localStorage.getItem("best"));With "95" saved, the paragraph says Best score: 120, and the console shows:
120best is now a let, because a new best score replaces it. On a first visit, ?? "0" makes the old best 0, so any score is saved.
Reread 21.2 Storage Holds Only Strings and 21.1 Saving Data in localStorage if your fix differed.
Question 21 · Tracing
isTask is the guard from tasks.dom.ts. Predict exactly what this program shows.
type Task = { title: string; done: boolean };
function isTask(value: unknown): value is Task {
return (
typeof value === "object" &&
value !== null &&
"title" in value &&
typeof value.title === "string" &&
"done" in value &&
typeof value.done === "boolean"
);
}
const samples = [
'{"title":"Read","done":false}',
'{"title":"Read"}',
'{"title":"Read","done":"no"}',
'{"title":"Read","done":true,"due":"Friday"}',
"null",
'["Read",false]',
];
for (const text of samples) {
const value: unknown = JSON.parse(text);
console.log(isTask(value));
}Check your reasoning
true
false
false
true
false
false{"title":"Read","done":false}: an object with a stringtitleand a booleandone, sotrue.{"title":"Read"}: line 9’s"done" in valueisfalse, so the guard stops there.{"title":"Read","done":"no"}:doneis a string, so line 10 fails.{"title":"Read","done":true,"due":"Friday"}:true. The guard checks the properties aTaskneeds and ignores extra ones, just as the checker accepts an object with extra properties where aTaskis expected.null:typeof nullis"object", so line 5 passes, but line 6 catches it.["Read",false]: an array is an object, but it has notitleproperty, so line 7 fails.
Reread 21.6 A Small Typed Storage Module and 21.4 Loading with JSON.parse into unknown if any line differed.
Question 22 · Short answer
A teammate wants to simplify staples.dom.ts by deciding whether to fetch the starter list with if (loadList(saved).length === 0) instead of if (saved === null). Describe a user who would be annoyed by that change, and one kind of saved data for which the change would actually be better.
Check your reasoning
A model answer:
- Annoyed: a user who bought everything and removed every item. Their saved list is
"[]", which loads as an empty list, so the teammate’s version fetches the staples and shows milk, bread, and eggs again on every reload. The user can never keep an empty list. With=== null, an empty saved list is respected. - Better: corrupted or wrong-shape data, such as
oops.savedis notnull, so the original version loads[]and shows an empty list; the teammate’s version would offer the starter items again, which is a friendlier recovery.
A correct answer separates “never saved” (null) from “saved, but empty” ("[]"), and notices that a broken value is neither. A version that does both would have loadList report the failure differently from a real empty list, for example by returning null for unusable data.
Reread 21.7 Fetching a Starter File from public and 21.5 Validating and Falling Back to Defaults if your answer differed.
Question 23 · Multiple choice
Ana uses the shopping list app on her laptop. Which statement is true?
- When she opens the app on her phone, her laptop’s list appears there too
- Her brother, using the same laptop and browser, can read her list in the developer tools
- If she clears her browsing data, the list is restored from
public/staples.jsonexactly as she left it - The list is safe from other scripts on the page because it is saved as JSON
Check your reasoning
B. Storage is plain text in one browser on one device, readable by anyone who uses that browser. That is fine for a shopping list and a reason never to store private data.
- A is wrong: each browser on each device has its own storage; nothing is sent anywhere.
- C is wrong: clearing browsing data deletes the saved list, so
getItemgivesnulland the app treats it as a first visit. It loads the starter list, not her list. - D is wrong: JSON is a text format, not a lock. Any script on the page can call
getItemandJSON.parse.
Reread 21.8 What Not to Store in the Browser and 21.7 Fetching a Starter File from public if you chose differently.
Go further
MDN’s guide covers localStorage in more detail, including its sibling sessionStorage (which forgets when the tab closes) and the storage event that tells other open tabs a value changed: MDN: Using the Web Storage API.
Reflection
Check each statement. If the answer is “not yet,” reread the linked subsection.
- I can save, load, and remove a value with setItem, getItem, and removeItem, and handle the null from getItem. Reread
- I can save and load numbers with String() and Number(), and spot the "205" bug. Reread
- I can save an array or an object with JSON.stringify and explain why String() is not enough. Reread
- I can load with JSON.parse into unknown and say why any is dangerous for saved data. Reread
- I can write a loader that falls back to a default when saved data is missing, corrupted, or the wrong shape. Reread
- I can keep storage in a small typed module with load and save functions, and save every time the state changes. Reread
- I can fetch a starter file from the public folder, but only on a first visit. Reread
- I can say what must never be stored in the browser and why. Reread