Lesson 4 of 5 · Client-Side Logic
Objects & JSON
Objects group related values under names; JSON is how those objects travel as text between programs.
This lesson is locked. You can read ahead, but finish earlier stops to earn progress.
Listen
Watch
Read
An object gives values names
An array stores ordered items; an object groups related values under keys:
const notebook = { id: 'notebook', name: 'Practice notebook', price: 12 };
console.log(notebook.name);
console.log(notebook['price']);Dot notation reads a known property; bracket notation can use a variable key. name is a string and price is a number. A missing property such as notebook.cost returns undefined; JavaScript does not guess that cost means price.
A const binding cannot be reassigned, but notebook.price = 14 changes a property of the same object. Be deliberate about mutation. A copy such as const alias = notebook refers to the same object, not an independent clone; editing alias.price also changes notebook.price.
Arrays of objects model product lists
const products = [
{ id: 'notebook', name: 'Practice notebook', price: 12 },
{ id: 'pen', name: 'Practice pen', price: 3 }
];
console.log(products[1].name);
console.log(products[0].price * 2);The first result is Practice pen; the second is 24. Read the chain from left to right: products[0] selects one object, .price selects its numeric field, then multiplication calculates a value. price belongs to a product, while a visitor's chosen quantity is interface state; they are not the same thing.
Use stable IDs to connect rows to data. If you sort products alphabetically, index 0 may become a different product. The id can still identify the same one. Repeated HTML ids are invalid: give each input a unique id and label, or use a data attribute carrying the stable product id.
Work one object into a row
For a selected practice product, a safe DOM pattern is:
const row = document.createElement('p');
row.textContent = `${notebook.name}: ${notebook.price}`;You then append it to your selected container. Put that small pattern inside the loop from the previous lesson to render every product. Do not insert names from unknown sources directly as innerHTML. In the calculator, add your own labelled input and keep a reliable association between that input and its product's price.
JSON is a data format, not a live object
JSON can represent objects, arrays, strings, numbers, booleans and null. It is commonly sent as text in an HTTP body or stored as text in localStorage. Networks can send other formats too; JSON is the convention used by these course examples, not the only way programs communicate.
{"id":"notebook","name":"Practice notebook","price":12}Compared with JavaScript object syntax, JSON requires double-quoted keys and strings. It does not allow comments, trailing commas, functions or undefined. A date commonly travels as a string and needs deliberate interpretation after parsing.
Convert and inspect the round trip
const text = JSON.stringify(products); console.log(typeof text); const restored = JSON.parse(text); console.log(Array.isArray(restored)); console.log(restored[0].price);
text is a string; restored is an array; the numeric field returns 12. Stringify does not save anywhere by itself. Parse does not fetch a URL or read storage by itself. Each performs one conversion.
JSON.parse('{broken}') throws a SyntaxError. A syntactically valid value like '"hello"' parses successfully into a string, but is not a list of products. Syntax validity and expected shape are separate questions. The storage and server-validation lessons develop recovery and validation; start recognising the difference now.
Check unknown shapes before using them
A lightweight guard for a single rehearsal object can check that it is non-null, typeof object, and that name is a string and price is a finite number. For a list, first use Array.isArray and then check its entries. Do not call map just because an API response “looks like data”.
If fields are optional, decide a deliberate fallback. A missing price should not silently become an authoritative zero-price product. For a harmless practice display, show an unavailable label; for a real write, reject invalid input server-side.
Guided practice
Create three of your own harmless product objects with stable IDs, labels and numeric values. Predict one direct property read and one multiplication, then run them. Stringify the array, inspect its text and parse it back. Confirm the array shape before iterating.
Temporarily change a field name in the display code: inspect the undefined result, then restore it. Temporarily use a string where a numeric price belongs and explain the type difference. Finally put a product name containing angle brackets through textContent and confirm it displays as text rather than becoming an HTML tag.
Ready for the calculator
You should be able to identify the list, one record and each field; iterate all records; attach quantity controls to the right records; and explain the difference between JSON text and parsed values. These are the data foundations of your next product, not optional branch knowledge.
Key terms
- Object
- Key: value pairs grouped under one name.
- Dot notation
- Read a value with user.name.
- JSON
- The text format objects travel in — double quotes required.
- stringify / parse
- Object to text, and text back to object.
Summary — copy into your notes
- Objects group named values; arrays of objects are everywhere.
- JSON is objects as text, with double quotes.
- stringify and parse convert between the two.