typestar

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

  1. Everything is a string: serialize on the way in.
  2. A quota error is a real possibility, so wrap the write.
  3. sessionStorage has the same API and a shorter life.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 2 in Forms & storage, step 8 of 13 in The browser.

← Previous Next →