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 05
Theory. Valid JSON is not the same as correct data. The text {"title":"Rent","amount":"500"} parses without error, but amount is a string and your code expects a number. [1,2] is valid JSON but not a record.
So after parse comes a second check — a "shape guard": the type of the value itself, required fields, and their types.
function isExpense(value) { if (typeof value !== "object" || value === null || Array.isArray(value)) return false; if (typeof value.title !== "string") return false; return typeof value.amount === "number" && Number.isFinite(value.amount); }
Only after the guard is it safe to use value.amount. Show a rejected value as "bad" and an accepted one as "ok".
Common mistake: typeof null is "object"; an array is also "object"; NaN is a number; accepting "500" as a number.
<pre id="raw-a">{"title":"Rent","amount":"500"}</pre><pre id="raw-b">{"title":"Rent","amount":500}</pre><pre id="raw-c">[1,2]</pre><p id="status-a"></p><p id="status-b"></p><p id="status-c"></p>Valid JSON does not guarantee the right shape — check types before use.
(empty)Press Run — HTML loads in a sandbox iframe; Stop removes the iframe (also kills infinite loops).
›