smartyfy.mrindigi.com

Web Development Pro | Lesson 025 | Objects and Data Modeling

Web Development Pro · Lesson 25 of 60

Module 3: JavaScript foundations

In this lesson

Prerequisites and learning outcomes

Complete lesson 24 first. This lesson builds on properties, identity, and references. By the end, you can model an event and update nested values with a clear ownership strategy. Plan 10–15 minutes for the core explanation and additional time for the worked practice.

Keep related facts together

Parallel arrays of titles, rooms, and capacities are fragile. If one array changes order independently, a room can become attached to the wrong workshop. An object groups named properties describing one record. An array of such objects represents a collection of records while preserving each record's internal relationships.

Begin by defining what one record represents: one workshop session in the fictional directory. Give it a stable id, a title, a category, and a capacity. The id is an internal identifier; the title is visitor-facing text that can change. Do not use the display title as the only identity if editing that wording should not create a different session.

Read and write properties deliberately

Dot notation is convenient for known property names. Bracket notation is useful when the key is stored in a variable or is not a simple identifier. Accessing a missing property produces undefined rather than automatically creating a meaningful default. Validate records before trusting fields that came from outside your program.

const workshop = {
  id: 'bike-101',
  title: 'Bicycle basics',
  category: 'repair',
  capacity: 12,
  venue: { room: 'River room', stepFree: true }
};
const updated = {
  ...workshop,
  capacity: 14,
  venue: { ...workshop.venue, room: 'Garden room' }
};
const { title, capacity } = updated;
console.log(`${title}: ${capacity}`);
console.log(workshop.venue.room);
console.log(updated.venue.room);

The outputs show Bicycle basics: 14, River room, and Garden room. The spread syntax copies the object's own enumerable properties into a new object. Later properties in the literal replace earlier properties with the same name, so capacity: 14 overrides the copied capacity. The venue is copied separately because it is nested.

Understand references before copying

Assigning const second = workshop does not clone the object. Both bindings refer to the same object, so changing second.capacity would be visible through workshop.capacity. This is often useful, but it can surprise you when a function appears to change a record owned by another part of the application.

The spread copy is shallow. If you write const copy = {...workshop}, then copy.venue and workshop.venue still refer to the same nested object. Changing copy.venue.room would affect the original venue too. The example explicitly creates a new venue object to isolate that edited branch while leaving unrelated primitive fields straightforward.

Do not describe every spread expression as a deep clone. Deep-copying arbitrary application objects has its own limitations and costs. Often the clearer solution is to copy only the branch being changed and keep a documented ownership model. For this small directory, immutable-style updates make state changes easier to trace without requiring a general cloning utility.

Model a collection of records

A workshop list can contain objects with the same field contract. Then filter can inspect category, map can extract titles, and find can locate a stable id. For example, workshops.find(item => item.id === 'bike-101') asks for one matching record. Handle undefined if the id is absent rather than immediately reading .title from a missing result.

Consistent field names matter. Mixing capacity, seats, and maxPeople for the same concept forces every consumer to guess. Choose one representation at the boundary and normalize external data into it. Also specify units where relevant: durationMinutes is clearer than duration if several units could be used.

A boolean such as stepFree should mean something precise. It might indicate a verified venue feature, or it might only repeat unverified source data. Code types do not establish real-world truth. For this course the data is explicitly fictional; in a real product, keep provenance and uncertainty separate from the shape of the record.

Use destructuring without hiding the source

Destructuring extracts named values into bindings, as shown for title and capacity. It can reduce repetition when a function uses several fields. It does not maintain a live link that updates the primitive binding whenever the object property changes later. The extracted value is the value read at that time.

Defaults in destructuring apply when the property is undefined, not when it is null or an empty string. Choose defaults that match the application contract, and do not use them to conceal malformed required data. If every event must have a title, silently replacing missing titles with an empty string can make a broken data source harder to detect.

Test identity and independence

Tests should check both the new result and the original input when a function promises not to mutate. A result can look correct while the original was accidentally changed. For the example, verify updated.capacity is fourteen, workshop.capacity remains twelve, and the two venue objects are distinct with their respective room names.

Also test missing lookups and unexpected fields when accepting records from elsewhere. A valid-looking object literal in your source is different from JSON downloaded from a service. Later lessons will validate data at that boundary before rendering it, reducing the chance that a missing property becomes a confusing interface failure.

The supplied Node test checks the example's outputs and reference relationships. It does not claim to validate every possible object or implement production data storage. Its purpose is to make shallow copying and explicit nested updates observable before you build stateful interfaces.

Worked practice

Worked exercise 1: Diagnose aliasing

Task: const second = workshop is followed by second.capacity = 20. What is workshop.capacity? Worked answer: twenty, because both bindings refer to the same object. If the original must stay unchanged, create a new object with the updated property instead of assigning another name to the same object.

Worked exercise 2: Repair a shallow nested update

Task: A spread copy changes copy.venue.room and unexpectedly changes the original. Worked answer: copy the venue branch too: venue: {...workshop.venue, room: 'Garden room'}. The outer copy alone did not create an independent nested object.

Worked exercise 3: Handle a missing id

Task: find returns undefined for an unknown workshop id. Worked answer: branch on the missing result before accessing its title, and present a useful “Workshop not found” outcome. Do not invent a record or let an uncontrolled property-access error become the interface's explanation.

Knowledge check

Question 1

Why group a session's fields in one object? A) To keep related facts together. B) To ensure that every grouped field has the same type. C) To guarantee real-world accuracy. D) To prevent every mutation automatically.

Check question 1: answer and explanation

Answer: A. A record preserves relationships that parallel arrays can accidentally lose.

Question 2

What does const second = workshop create? A) A deep clone. B) A new reference to the same object. C) A frozen copy. D) A shallow clone of the outer object.

Check question 2: answer and explanation

Answer: B. Assignment copies the reference, not the object's complete contents.

Question 3

What kind of copy does object spread normally make? A) Recursive for every nested object. B) A copy of both own and inherited properties. C) A shallow property copy. D) A copy without any shared references by definition.

Check question 3: answer and explanation

Answer: C. Nested object references remain shared unless copied deliberately.

Question 4

When does a destructuring default apply? A) For every falsy value. B) Only for zero. C) Only for an empty string. D) When the property value is undefined.

Check question 4: answer and explanation

Answer: D. Null and other explicit values do not trigger that default automatically.

Question 5

What should an immutable-style update test check? A) Both the new result and the unchanged original. B) Only the console text. C) Only that the outer object is a different reference. D) Only that the returned object has the expected property names.

Check question 5: answer and explanation

Answer: A. A correct-looking result can conceal accidental mutation of its input.

Sources and further reading