JavaScript AcademyProfessional Engineering
Level 2 · Core DevelopmentModule 8: Objects and Structured DataLesson 40 of 150About 55 minutes

Lesson 40: Modeling real-world information

01Opening question

Before writing any code for a library app, someone has to decide what a book, a member and a loan look like. How do you model real-world information well?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

Records are linked by id, like rows in a database.

const members = [{ id: "m1", name: "Ada" }];
const books = [{ id: "b1", title: "Dune" }];
const loans = [{ bookId: "b1", memberId: "m1", due: "2026-12-10" }];
const loan = loans[0];
const who = members.find((m) => m.id === loan.memberId);
console.log(`${who.name} has book ${loan.bookId}`);

03Objective and prerequisites

Learning objective: Model real-world entities as objects and collections, choose property names and types, link records by id, write factory and validation functions, and derive values instead of storing duplicates.

You need: Lesson 36: Creating JavaScript objects, Lesson 37: Properties, methods and dynamic keys, Lesson 38: Nested objects and arrays, Lesson 39: Object copying and reference behavior

Skills practised: Objects, Data modeling.

04Explanation

Start by listing the entities (things) in the problem, such as Book, Member and Loan, and the properties each one needs.

Pick clear names and consistent types: price is always a number, dueDate always an ISO date string, tags always an array.

Link records by id instead of copying data: a loan stores memberId, not the member's name, so a name change is made in one place.

Do not store what you can calculate: store quantity and unitPrice, and derive lineTotal with a function.

05Definitions

Entity
A kind of thing in the problem, such as a book or a customer.
Data model
The set of entities, their properties and how they are linked.
Foreign key
A property that stores another record's id to link them.
Factory function
A function that creates objects with a consistent shape.
Derived value
A value calculated from stored data instead of stored itself.

Open the full glossary

06Visual learning object

Nested object explorer. Explore a modelled dataset path by path and see how records link through ids.

Loading the interactive object…

Open the full Nested object explorer page with its guided experiment.

07Examples

ex-040-01Entities and links Browser-executable JavaScript

Loans link a member and a book by id.

const members = [{ id: "m1", name: "Ada" }, { id: "m2", name: "Linus" }];
const books = [{ id: "b1", title: "Dune" }, { id: "b2", title: "Emma" }];
const loans = [{ bookId: "b2", memberId: "m1" }];
for (const loan of loans) {
  const m = members.find((x) => x.id === loan.memberId);
  const b = books.find((x) => x.id === loan.bookId);
  console.log(`${m.name} borrowed ${b.title}`);
}
Sample input
None
Expected output
Ada borrowed Emma
Common mistake
Copying the member's name into every loan.
Try this
Add a loan for Linus.
Source
examples/ex-040-01-entities.js

ex-040-02A factory with defaults and validation Browser-executable JavaScript

Every created object has the same shape.

function createBook({ title, author, year = null, tags = [] }) {
  if (!title || !title.trim()) throw new Error("Title is required");
  return { id: "b" + Math.abs(title.length * 7919 % 1000), title: title.trim(), author: author ?? "Unknown", year, tags: [...tags] };
}
const b = createBook({ title: " Dune ", author: "Frank Herbert", tags: ["sci-fi"] });
console.log(b.title, b.year, b.tags);
console.log(Object.keys(createBook({ title: "Emma" })).join(","));
Sample input
None
Expected output
Dune null ["sci-fi"] id,title,author,year,tags
Common mistake
Creating objects by hand with slightly different keys each time.
Try this
Reject a year in the future.
Source
examples/ex-040-02-factory.js

ex-040-03Derive, do not duplicate Browser-executable JavaScript

Line totals and the order total are calculated, never stored.

const order = { lines: [{ sku: "A", qty: 2, unitCents: 450 }, { sku: "B", qty: 1, unitCents: 1200 }] };
const lineTotal = (l) => l.qty * l.unitCents;
const orderTotal = (o) => o.lines.reduce((s, l) => s + lineTotal(l), 0);
console.log(orderTotal(order));
order.lines[0].qty = 3;
console.log((orderTotal(order) / 100).toFixed(2));
Sample input
None
Expected output
2100 25.50
Common mistake
Storing a total that goes stale when a quantity changes.
Try this
Add a 10% tax function.
Source
examples/ex-040-03-derived.js

ex-040-04One status instead of many booleans Browser-executable JavaScript

A single status cannot contradict itself.

const loans = [
  { id: 1, status: "active", due: "2026-12-01" },
  { id: 2, status: "returned", due: "2026-11-20" },
  { id: 3, status: "active", due: "2026-11-25" }
];
const today = "2026-11-30";
const overdue = loans.filter((l) => l.status === "active" && l.due < today).map((l) => l.id);
console.log(overdue);
Sample input
None
Expected output
[3]
Common mistake
Using isActive, isReturned and isOverdue booleans that can all be true at once.
Try this
Count active loans.
Source
examples/ex-040-04-status-field.js

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Link by id

Look up a related record instead of using stale copied data.

const customers = [{ id: "c1", name: "Ada Lovelace" }];
const orders = [{ id: "o1", customerId: "c1", customerName: "Ada Byron" }];
console.log(orders[0].customerName);

Derive the totals

Replace stored totals with functions.

const cart = { lines: [{ name: "Tea", qty: 2, unit: 3 }, { name: "Cake", qty: 1, unit: 4 }] };
// TODO: write lineTotal(line) and cartTotal(cart); then change Tea to 3 and print the total

Event booking model

Design entities, factories and derived values for a small domain.

// Model: events { id, title, capacity } and bookings { id, eventId, name, seats }
const events = [];
const bookings = [];

09Prediction

Commit to an answer first, then run the real code to compare.

const items = [{ qty: 2, price: 3, total: 6 }];
items[0].qty = 4;
console.log(items[0].total, items[0].qty * items[0].price);

What is printed?

10Debugging investigation

Renamed products still show old names in orders

The "Mug" product was renamed "Travel Mug", but order history still shows "Mug".

const products = [{ id: "p1", name: "Mug" }];
const orders = [{ id: "o1", lines: [{ productId: "p1", name: "Mug", qty: 2 }] }];
products[0].name = "Travel Mug";
function lineLabel(line) {
  return `${line.name} x${line.qty}`;
}
const label = lineLabel(orders[0].lines[0]);
console.log(label);

More cases in the Debugging Detective Laboratory

11Practical scenario

Designing a clinic booking system

Before building screens, a team models patients, practitioners and appointments as linked records with ids, decides that an appointment has one status field, and agrees that durations and totals are derived. Every later feature builds on this model.

const appt = { id: "a1", patientId: "p1", status: "booked", start: "2026-12-02T09:00", mins: 30 };
console.log(appt.status, appt.mins);

12Knowledge check

1. Why does a loan store memberId instead of the member's name?

  • Ids are shorter
  • So the member's details live in one place and stay correct
  • Names are not allowed
  • It is faster to print

2. Which value should be derived rather than stored?

  • A product's name
  • An order's total
  • A customer's email
  • A book's title

3. What is risky about this model?

{ isPaid: true, isRefunded: true, isPending: true }
  • Nothing
  • The booleans can contradict each other
  • Too few properties
  • Ids are missing

4. What does a factory function guarantee?

  • Faster code
  • Every created object has the same shape, defaults and validation
  • Objects cannot change
  • Unique emails

5. How should money be stored to avoid rounding errors?

  • As strings like "$4.50"
  • As integer cents
  • As floats only
  • As booleans

6. Which property name and type is best for when a loan is due?

  • due: "next Tuesday"
  • dueDate: "2026-12-10"
  • d: 12
  • dueDateText: "10/12"

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • Link by id: Prints the current name; Uses customerId
  • Derive the totals: Prints 10 then 13; No stored total
  • Event booking model: Prints 1 then the error; Two bookings stored; seatsLeft is derived
  • ex-040-01: output matches the documented expected output
  • ex-040-02: output matches the documented expected output
  • ex-040-03: output matches the documented expected output
  • ex-040-04: output matches the documented expected output

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-02-core-development/module-08-objects-and-structured-data/lesson-040-modeling-real-world-information/. Every example on this page is generated from those files.

These links open the files in the GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Engineering-Academy). You can also use the ZIP download above.

15Summary and next steps

  • List entities and their properties first.
  • Link records by id; do not copy shared data.
  • Use factories for consistent shapes and validation.
  • Derive totals and statuses from stored facts.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation data modelling
Context: I am learning data modelling in JavaScript.
Task: Help me model a small library or booking system as entities, properties and id links, explaining each choice.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code prediction data modelling drill
Context: I have practised data modelling.
Task: Show me five data models and ask me to spot duplicated or contradictory data.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
Debugging data modelling bug
Context: My stored totals and statuses keep going out of date.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generation data modelling practice
Context: I finished the data modelling exercises.
Task: Specify two small domains for me to model, with the queries the model must support.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code review data modelling review
Context: Here is my code that uses data modelling.
Task: Review my data model for duplicated data, unclear names and values that should be derived.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.