Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
Loading…
Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
Loading…
Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
JAVASCRIPT STORAGE / CHAPTER 06 / Learn / LESSON 04
Theory. JSON.parse throws a SyntaxError on invalid text — a missing quote, a trailing comma, a cut-off end. If you do not catch it, the script stops and the page stays half done.
The fix is try/catch around parse:
let data = null; try { data = JSON.parse(text); } catch (error) { status.textContent = "bad-json"; }
The error is an expected case, not a panic: the data comes from outside (storage, file, network) and may be damaged. Show a clear state to the user — do not stay silent and do not show half-read data.
A small function helps: parseOrNull(text) returns data or null. Then you check for null.
Common mistake: try/catch around more code than needed; an empty catch with no message; putting data into the DOM before it is clear that parse succeeded.
<pre id="raw-a">{"title":"Rent","amount":500}</pre><pre id="raw-b">{"title":"Rent","amount":</pre><p id="status-a"></p><p id="status-b"></p><p id="shown"></p>Damaged text is an expected case — catch the SyntaxError and show a clear state.
(empty)Press Run — HTML loads in a sandbox iframe; Stop removes the iframe (also kills infinite loops).
›