appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

Errors, storage and events

Lesson 4 of 410 minIntermediate

Handle failure, remember data in the browser and react to user actions safely.

Errors

try {
  const data = JSON.parse(text);
} catch (err) {
  console.error("invalid JSON:", err.message);
}

window.addEventListener("unhandledrejection", (e) => console.error("unhandled", e.reason));

Throw Error objects (throw new Error("message")), not strings, because errors carry a stack trace.

Web storage

localStorage.setItem("theme", "dark");
const theme = localStorage.getItem("theme");
localStorage.setItem("cart", JSON.stringify({ items: [1, 2] }));
const cart = JSON.parse(localStorage.getItem("cart") ?? "{}");
  • localStorage persists until cleared. sessionStorage lasts for the tab.
  • Values are strings, so convert objects with JSON.stringify and JSON.parse.
  • It is readable by any script on your page. Never store passwords or access tokens that must stay secret.

Events

document.querySelector("#list").addEventListener("click", (e) => {
  const item = e.target.closest("li");
  if (item) console.log("clicked", item.dataset.id);
});

Event delegation puts one listener on a parent instead of many on the children. It works for items added later and uses less memory.

CarefulNever insert user-provided text with innerHTML. It runs any HTML or script inside it (XSS). Use textContent, or sanitise the content first.

Test yourself

Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.

1. Why use textContent instead of innerHTML for user text?
2. What type are values stored in localStorage?
3. What is event delegation?

Key terms