Errors, storage and events
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") ?? "{}");localStoragepersists until cleared.sessionStoragelasts for the tab.- Values are strings, so convert objects with
JSON.stringifyandJSON.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.