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 08
Theory. CRUD = Create, Read, Update, Delete. For records you need a STABLE id — a number that does not change and is never reused. The array index is NOT a good id: after a delete everything after it shifts.
New id: the largest id + 1 (or 1 for an empty list).
function nextId(items) { let max = 0; for (const item of items) if (item.id > max) max = item.id; return max + 1; }
Operations: - Add: items.push({ id: nextId(items), title, amount }). - Edit: find the record by id (find) and change the field. - Delete: items = items.filter(item => item.id !== id).
After EVERY change: save(items) and render. If you keep data only in memory and forget save, the change disappears on reload.
Keep the key order the same when you write records: id, title, amount — the data stays predictable.
Common mistake: length + 1 as an id (it duplicates after a delete); searching by index; forgetting save after an edit.
<form id="f"><input id="title" name="title" type="text"><input id="amount" name="amount" type="text"><button type="submit">Add</button></form><input id="del-id" type="text"><button id="del" type="button">Delete</button><input id="edit-id" type="text"><input id="edit-title" type="text"><button id="edit" type="button">Rename</button><ul id="list"></ul><p id="count"></p>{
"expenses": "[{\"id\":1,\"title\":\"Rent\",\"amount\":500},{\"id\":2,\"title\":\"Food\",\"amount\":120},{\"id\":3,\"title\":\"Fun\",\"amount\":60}]"
}Stable ids survive deletes; the index does not. Save after every change.
(empty)Press Run — HTML loads in a sandbox iframe; Stop removes the iframe (also kills infinite loops).
›