localStorage in JavaScript
Strings only, synchronous, and it can throw when full.
const KEY = "ts_progress";
function loadProgress() {
try {
return JSON.parse(localStorage.getItem(KEY) ?? "{}");
} catch {
return {}; // corrupt or unparsable: start fresh
}
}
function saveProgress(progress) {
try {
localStorage.setItem(KEY, JSON.stringify(progress));
return true;
} catch (error) {
console.warn("could not save:", error.name);
return false;
}
}
function clearProgress() {
localStorage.removeItem(KEY);
return localStorage.getItem(KEY) === null;
}
How it works
- Everything is a string: serialize on the way in.
- A quota error is a real possibility, so wrap the write.
sessionStoragehas the same API and a shorter life.
Keywords and builtins used here
JSONcatchconstfunctionreturntry
The run, in numbers
- Lines
- 24
- Characters to type
- 467
- Tokens
- 107
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 64 seconds.
Step 2 of 2 in Forms & storage, step 8 of 13 in The browser.