JavaScript AcademyProfessional Engineering
Level 2 · Core DevelopmentModule 6: Arrays and CollectionsLesson 30 of 150About 55 minutes

Lesson 30: Building collection-based applications

01Opening question

A to-do app adds tasks, completes them, removes them and counts what is left. How do you structure a small application around one array?

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

One array holds the state. Small functions change it in one well-defined way each.

const tasks = [];
function addTask(title) {
  tasks.push({ id: tasks.length + 1, title, done: false });
}
addTask("Buy milk");
addTask("Call Ada");
console.log(tasks.length, tasks[1].title);

03Objective and prerequisites

Learning objective: Build a collection-based application: keep state in an array of objects, write functions that add, update, remove and summarise items, and test each operation.

You need: Lesson 26: Creating and accessing arrays, Lesson 27: Adding and removing elements, Lesson 28: Searching and sorting arrays, Lesson 29: Iterating over collections

Skills practised: Arrays, Working with collections, Application design.

04Explanation

Many applications are a collection (an array of objects) plus operations on it: add, find, update, remove, list and count.

Give each item a unique id so you can find it reliably, even when titles repeat or the order changes.

Write one function per operation: addTask, completeTask(id), removeTask(id), summary(). Each function does one job and can be tested on its own.

Keep display separate from data. A render() or printList() function reads the array and prints it; the other functions only change data.

05Definitions

Collection
A group of similar items, usually stored as an array of objects.
State
The data an application holds at a moment in time.
Unique id
A value that identifies exactly one item in a collection.
CRUD
Create, Read, Update, Delete: the basic operations on a collection.
Render
Turning data into output that a person sees.

Open the full glossary

06Visual learning object

Array operation explorer. Try each collection operation on a sample array and compare the returned value with the array afterwards.

Loading the interactive object…

Open the full Array operation explorer page with its guided experiment.

07Examples

ex-030-01Add and list Browser-executable JavaScript

A counter makes ids unique; printList only reads.

const tasks = [];
let nextId = 1;
function addTask(title) {
  const task = { id: nextId++, title, done: false };
  tasks.push(task);
  return task;
}
function printList() {
  for (const t of tasks) console.log(`${t.done ? "[x]" : "[ ]"} ${t.id} ${t.title}`);
}
addTask("Buy milk");
addTask("Call Ada");
printList();
Sample input
None
Expected output
[ ] 1 Buy milk [ ] 2 Call Ada
Common mistake
Using tasks.length + 1 for ids, which repeats after a removal.
Try this
Add a third task.
Source
examples/ex-030-01-add-and-list.js (repository pending publication)

ex-030-02Update by id Browser-executable JavaScript

find returns the object itself, so changing it updates the collection.

const tasks = [
  { id: 1, title: "Buy milk", done: false },
  { id: 2, title: "Call Ada", done: false }
];
function completeTask(id) {
  const task = tasks.find((t) => t.id === id);
  if (!task) return false;
  task.done = true;
  return true;
}
console.log(completeTask(2), completeTask(9));
console.log(tasks[1].done);
Sample input
None
Expected output
true false true
Common mistake
Updating a copy and wondering why the list did not change.
Try this
Write a renameTask(id, title) function.
Source
examples/ex-030-02-update-by-id.js (repository pending publication)

ex-030-03Remove by id Browser-executable JavaScript

findIndex locates the item; splice removes it.

const tasks = [
  { id: 1, title: "A" },
  { id: 2, title: "B" },
  { id: 3, title: "C" }
];
function removeTask(id) {
  const i = tasks.findIndex((t) => t.id === id);
  if (i === -1) return null;
  return tasks.splice(i, 1)[0];
}
console.log(removeTask(2).title);
console.log(tasks.map((t) => t.id).join(","));
console.log(removeTask(2));
Sample input
None
Expected output
B 1,3 null
Common mistake
Calling splice(-1, 1) when the id is missing, which removes the last item.
Try this
Return a clear message instead of null.
Source
examples/ex-030-03-remove-by-id.js (repository pending publication)

ex-030-04Summarise the collection Browser-executable JavaScript

A summary function reads the state and returns numbers.

const tasks = [
  { id: 1, done: true },
  { id: 2, done: false },
  { id: 3, done: true }
];
function summary(list) {
  let done = 0;
  for (const t of list) if (t.done) done++;
  return { total: list.length, done, left: list.length - done };
}
const s = summary(tasks);
console.log(`${s.done} of ${s.total} done, ${s.left} left`);
Sample input
None
Expected output
2 of 3 done, 1 left
Common mistake
Printing inside summary, which makes it hard to reuse.
Try this
Add a percentage to the summary.
Source
examples/ex-030-04-summary.js (repository pending publication)

08Guided exercises

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

Unique ids

Generate ids that stay unique after removals.

const notes = [];
function addNote(text) {
  notes.push({ id: notes.length + 1, text });
}
addNote("one");
addNote("two");
notes.splice(0, 1);
addNote("three");
console.log(notes.map((n) => n.id).join(","));

Toggle a task

Update an item found by id.

const tasks = [
  { id: 1, title: "Plan", done: false },
  { id: 2, title: "Build", done: true }
];
function toggleTask(id) {
  // TODO: flip done for the task with this id and return the new value, or null if not found
}
console.log(toggleTask(1), toggleTask(2), toggleTask(5));

Reading list application

Build add, finish, remove and summary operations on one collection.

const books = [];
let nextId = 1;
// Write addBook(title, pages), finishBook(id), removeBook(id) and stats()
// stats() returns { count, finished, pagesRead } where pagesRead counts finished books only

09Prediction

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

const list = [{ id: 1 }, { id: 2 }];
const i = list.findIndex((x) => x.id === 3);
list.splice(i, 1);
console.log(list.map((x) => x.id));

What is printed?

10Debugging investigation

Deleting an unknown contact deletes the last one

A stale button tries to delete contact 7, which no longer exists, and the last contact in the list disappears.

const contacts = [
  { id: 1, name: "Ada" },
  { id: 2, name: "Grace" },
  { id: 3, name: "Linus" }
];
function removeContact(id) {
  const i = contacts.findIndex((c) => c.id === id);
  contacts.splice(i, 1);
}
removeContact(7);
console.log("Contacts:", contacts.map((c) => c.name).join(", "));

More cases in the Debugging Detective Laboratory

11Practical scenario

Event sign-up list

A community event keeps attendees in an array of objects. Organisers add people, mark check-ins by id, remove cancellations and see live counts, all through small, tested functions.

const people = [{ id: 1, in: false }, { id: 2, in: true }];
const checkedIn = people.filter((p) => p.in).length;
console.log(`${checkedIn} of ${people.length} checked in`);

12Knowledge check

1. Why give each item an id?

  • Arrays require it
  • To find the exact item even if titles repeat or order changes
  • To sort faster
  • To save memory

2. What goes wrong when id 9 does not exist?

const i = items.findIndex((x) => x.id === 9);
items.splice(i, 1);
  • Nothing
  • splice(-1, 1) removes the last item
  • An error is thrown
  • The array is cleared

3. What is printed?

const a = [{ id: 1, done: false }];
a.find((t) => t.id === 1).done = true;
console.log(a[0].done);
  • true
  • false
  • undefined
  • An error

4. What does CRUD stand for?

  • Create, Read, Update, Delete
  • Copy, Run, Undo, Debug
  • Count, Remove, Use, Display
  • None

5. Why separate render() from data functions?

  • It is required
  • Data logic can be tested without output, and display can change independently
  • It is faster
  • It uses less code

6. Which id strategy is safest?

  • length + 1
  • A counter that only increases
  • The item title
  • Math.random()

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.

  • Unique ids: Ids stay unique; Uses a counter
  • Toggle a task: Prints the results; State updated
  • Reading list application: Prints the stats; Unknown id is rejected; stats returns an object
  • ex-030-01: output matches the documented expected output
  • ex-030-02: output matches the documented expected output
  • ex-030-03: output matches the documented expected output
  • ex-030-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-06-arrays-and-collections/lesson-030-building-collection-based-applications/. Every example on this page is generated from those files.

The GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Academy) has not been published yet, so these links will work once it is. Until then, use the ZIP download above.

15Summary and next steps

  • Applications often manage an array of objects.
  • Give items unique ids from a counter.
  • One small function per operation; check for not-found cases.
  • Keep rendering separate from data changes.

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 collection-based applications
Context: I am learning collection-based applications in JavaScript.
Task: Show me how to design a small to-do application around one array of objects with add, complete, remove and summary functions.
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 collection-based applications drill
Context: I have practised collection-based applications.
Task: Give me five sequences of collection operations and ask what the final state is.
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 collection-based applications bug
Context: Removing an item from my list sometimes removes the wrong one.
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 collection-based applications practice
Context: I finished the collection-based applications exercises.
Task: Specify two small collection applications (contacts, inventory) with operations and expected output.
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 collection-based applications review
Context: Here is my code that uses collection-based applications.
Task: Review my collection functions for id handling, not-found cases and separation of display from data.
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.