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 07
Theory. A list of records is stored as ONE key with JSON text, for example key "expenses" holding '[{"title":"Rent","amount":500}]'. The pattern is always the same:
1. Load: const raw = window.labStorage.getItem("expenses"); if null → empty array, else JSON.parse(raw). 2. Change in memory: items.push(record). 3. Save: window.labStorage.setItem("expenses", JSON.stringify(items)). 4. Render: show items in the list.
After a reload the code goes through step 1 and restores the list. So LOADING is part of the program, not only the save.
Small examples:
function load() { const raw = window.labStorage.getItem("expenses"); return raw === null ? [] : JSON.parse(raw); } function save(items) { window.labStorage.setItem("expenses", JSON.stringify(items)); }
Common mistake: writing only the new record instead of the whole array; forgetting Number for the amount; rendering before loading.
<form id="f"><input id="title" name="title" type="text"><input id="amount" name="amount" type="text"><button type="submit">Add</button></form><ul id="list"></ul>{
"expenses": "[{\"title\":\"Rent\",\"amount\":500}]"
}Load → change → save the whole array → render. A reload goes through the load.
(empty)Press Run — HTML loads in a sandbox iframe; Stop removes the iframe (also kills infinite loops).
›