JAVASCRIPT / LESSON 14

Remember a preference with browser storage

Save strings, restore validated data, and handle unavailable storage.

Content updated

By the end, you can…

  • Browser storage is optional local persistence, not a permanent database or a place for secrets.
  • Predict the example's result, change one part, and verify the behavior in your own script.
Before you begin

One idea at a time

Variables disappear when a page reloads. Web Storage can keep small string values under named keys. localStorage normally survives browser restarts, while sessionStorage is scoped to a tab's page session and survives reloads within it. Neither is permanent: users can clear data, private browsing changes its lifetime, and browser policies can block access.

Storage belongs to an origin: scheme, host, and port. In http://127.0.0.1:8000, http is the scheme, 127.0.0.1 the host, and 8000 the port. Keep this address the same between tests. A different site cannot simply read your origin's storage through this API. Use a local HTTP server for predictable practice instead of relying on file URL behavior. Keep the page usable when storage fails, and do not put passwords, access tokens, or sensitive personal details in these examples.

What to remember first

Remember first

Browser storage is optional local persistence, not a permanent database or a place for secrets.

Read the code before trying it

condition ? first : secondChoose a value
The conditional operator evaluates the condition and chooses only one branch. saved === "dark" ? "dark" : "light" keeps dark and otherwise chooses light.
throw new Error("Storage blocked")Simulate a failure
new Error creates an error value with a message. throw raises it so the nearest active catch handles it. The simulation deliberately uses this instead of changing your real storage permissions.
localStorage.setItem("theme", "dark")Save a string under a key
Saving another value under the same key replaces it. Objects need JSON serialization first.
localStorage.getItem("theme")Read a stored string
An absent key returns null, not undefined. Validate the value before applying it.
localStorage.removeItem("theme")Remove your own key
Prefer removing a named key over clear(), which removes every key in that storage area.
sessionStorageUse tab-session storage
It offers the same methods but a different lifetime. Closing the tab normally ends that session.
try / catchKeep failure recoverable
Access and writes can throw. Fall back to a default and keep the current interaction working.

Walk through an example

javascript
try {
  const saved = localStorage.getItem("tuklas-demo-theme");
  const theme = saved === "dark" ? "dark" : "light";
  console.log(theme);
} catch {
  console.log("Storage unavailable; using light.");
}

The local example only reads the dedicated preference key and accepts just the recognized dark value. It does not save dark again on every reload; the separate save-once task step lets you test restoration and removal. All other values fall back to light. If access fails, catch logs the fallback instead of stopping the rest of your page. Remove the demonstration key when you finish experimenting.

See it happen: try a small change

Remember a preference with browser storage: try it

Predict the result, choose a version, then compare the code and output. Try the controls when the example has them. Each version starts fresh.

Code to notice

const memory = {};
const storage = {
  setItem(key, value) {
    memory[key] = String(value);
  },
  getItem(key) {
    return memory[key] ?? null;
  },
  removeItem(key) {
    delete memory[key];
  },
};
storage.setItem("theme", "dark");
console.log(storage.getItem("theme"));
storage.removeItem("theme");
console.log(storage.getItem("theme"));

Live result

Lesson example
index.htmlPreview

What changed: Memory-only simulation: dark is saved and read, then removal returns null. It does not persist after a preview reset.

Look a little closer

To save an array, stringify it before setItem. When reading, handle the missing-key case, parse inside try/catch, and use Array.isArray(data) to check whether the parsed value is an array, then a for...of loop and typeof to inspect each item. A successful JSON parse alone does not mean the saved shape is usable. Data may have been written by an older version of your page.

The interactive preview below uses an explicitly labeled memory-only storage simulation because the isolated preview cannot access your site's storage. Its object implements the same three operations for learning, but resets when you choose a variant or reload the preview. To test actual persistence, run the localStorage code above in your own local project and reload that page.

Inside the simulation, String(value) converts a supplied value to text, matching the string-only storage interface. delete memory[key] removes that property from the memory object. The ?? null fallback returns null for a missing key. These lines implement our teaching substitute; you do not need them when using the actual localStorage methods.

Set up a local address before testing persistence

A local server serves files from your computer to the browser. Open your project folder in your editor and use its local preview server if available. Keep the http://localhost or http://127.0.0.1 address it provides, including the port. A file:// address does not have dependable storage behavior across browsers.

If Python 3 is already installed, open a terminal in the folder containing index.html and script.js and run the command below. Open http://127.0.0.1:8000/ in your browser. Keep the terminal open; Ctrl+C stops the server. If you do not have a server tool yet, use the embedded simulations now and return to the reload test later.

text
python -m http.server 8000 --bind 127.0.0.1

Try it in your own project

Use the local-server setup in this lesson and keep the same address between runs. Save the preference once through that page’s Console; leave only the read-and-fallback example in script.js. Reload, remove the key in the Console, and reload again. The embedded memory simulation cannot test persistence.

The interactive preview runs in its own isolated document. Its Output panel mirrors console.log messages; it is not a full DevTools console. Choosing another version or resetting starts a fresh example and does not edit your local files. Read any simulation label: storage and request demonstrations explain their offline substitutes, while the written local examples use the real browser APIs.

A common wrong turn

Storing an object directly usually produces the text [object Object], which cannot recover its properties. Storage is also synchronous, so avoid large frequent writes. Keep your own key names distinctive and never call clear just to reset one exercise preference.

Your turn: remember a preference with browser storage

Save and restore a light-or-dark preference in your local project without breaking the page when storage is unavailable.

Try this in your own HTML and JavaScript files, then open the page in a browser. There is no separate checked practice for this task yet.

  1. Use the Set up a local address instructions in this lesson. Run localStorage.setItem("tuklas-demo-theme", "dark") once in that page’s Console, then reload with the read-only script above. Expect dark.
  2. Read the key on a fresh page load; accept only light or dark and use light for anything else.
  3. Run localStorage.removeItem("tuklas-demo-theme") once in the Console and reload. Expect light. Use the unavailable-storage preview to test the failure path without changing browser settings.

Go to the source

Examples are authored for Tuklas and checked with code and reference documentation. This is not a claim of independent human review. Suggest a correction.