Browser storage and error handling

ECMAScript 2026

The browser can keep small values for a page to use again. Loading or converting those values can fail. Learn to read storage and give a useful message when an operation fails.

On this page

Save and read a value with localStorage

localStorage stores strings by key for the current origin, which is the combination of protocol, host, and port. getItem returns null for a missing key. Convert an object with JSON.stringify before saving and JSON.parse after reading. Use sessionStorage when the data is scoped to one browser tab and should end with its session.

How to try it Open a normal HTTP(S) page you own, such as the local server example. Open Developer Tools → Console and run the code for that page. Browser privacy settings may disable storage in some contexts.

localStorage.setItem("docs-product-example", JSON.stringify({ product: "Pen" }));
const saved = localStorage.getItem("docs-product-example");
console.log(saved === null ? "No saved product" : JSON.parse(saved).product);

What to expect It prints Pen. Reload the same HTTP(S) page and run localStorage.getItem("docs-product-example") to see it persist. Use removeItem with the same key to remove it.

Respond when an operation throws

An exception interrupts the current operation. Code inside try runs first. If it throws, the catch block receives the error. Handle failures where you can show a useful message or choose a safe default.

How to try it Open a browser tab, then open Developer Tools → Console. Type the example or paste it into the Console after reviewing it, then run it. Reload before repeating declarations with the same names.

try {
  const saved = JSON.parse("{broken}");
  console.log(saved);
} catch (error) {
  console.log("Could not read saved data:", error.name);
}

What to expect The example prints “Could not read saved data: SyntaxError”. Replace {broken} with valid JSON to make the try block finish.

Official references