LESSON 21 · BEGINNER4 min read

Project: Task Tracker

Build an in-memory task tracker with stable ids, filters, and JSON import and export.

ES2024 / Node.js 20+Free to readModule 4 of 19
YOUR NEXT SMALL WINS

By the end, you’ll be able to…

  • Model tasks as objects inside a private array with stable numeric ids.
  • Implement add, complete, remove, list, and filter operations with array methods.
  • Export and import JSON while validating every record before replacing state.

01The tracker contract

You will build an in-memory task tracker as a factory. createTaskTracker(initialTasks) returns methods add, complete, remove, list, toJSON, and loadJSON. Tasks are objects with a numeric id, a title, and a boolean done. IDs are stable and never reused during a session. The factory hides the array, so every change goes through a small set of operations you can test.

Build in four steps: initialize private state and the next id, add tasks with validated titles, complete and remove by id, then filter and serialize. Return copies from list and add so callers cannot mutate internal records by accident. loadJSON replaces the current list only after every record passes validation. The returned methods are the only public surface, so tests can exercise behavior instead of reaching into data.

tracker-check.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

02Step 1: Store tasks and create stable ids

Tasks live in a private array. The constructor copies each initial task, which prevents the caller's array and objects from becoming aliases of internal state. nextId is one more than the largest id already present, so importing data does not cause a collision. A tracker with no initial tasks starts nextId at 1. The counter only moves forward, even across an import, so a removed id is not reused later.

add trims the title and rejects an empty string. complete and remove return booleans, which lets the caller distinguish success from a missing id. list filters without changing the stored order and maps each result into a new object.

loadJSON validates the whole array before assigning it. If one record is malformed, the function throws and the existing tasks remain untouched, which is easier to reason about than a partial import.

task-tracker.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

03Step 2: Complete, remove, filter, and round-trip

The example adds two tasks, completes the first, and prints only the open ones. The export is a string, so it can be written to a file or stored in local storage. Importing it later restores titles, ids, and completion flags.

Notice that list returns copies. Mutating the array returned by list, or one of its task objects, does not rewrite the tracker's private records. When you need a change, call complete or remove with the stable id. If the id is wrong, the operation reports failure instead of guessing which task was meant. This makes the tracker safe to pass to a display function that might try to edit its input.

tracker-usage.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

04Review checklist

Test each operation with a missing id, an empty title, and a completed task. Completing twice should still report true if the task exists, while removing it twice should report false the second time. Filtering should return all, open, or done tasks without changing the stored order.

Round-trip the export through loadJSON and confirm that ids continue after the largest restored id. Feed malformed JSON and a malformed task shape; both should fail without replacing existing data. Finally, check that a task returned by list cannot mutate the tracker.

tracker-review.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
LET IT CLICK

The ideas worth keeping.

  • A private array and a monotonic id counter give the tracker stable, testable state.
  • map, filter, find, and findIndex express each operation without leaking internal objects.
  • Validate a complete JSON import before replacing state so failures cannot corrupt the tracker.
TURN UNDERSTANDING INTO SOMETHING YOU CAN DO

Make it yours.

Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.

01

Exercise 1: Mark a task complete without mutating

Write completeTask(tasks, id) that returns a new array where the matching task has done set to true. Return null when no task has that id. The input array and its task objects must remain unchanged.

your_turn_1.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.jsJavaScript
function completeTask(tasks, id) {  let found = false;  const updated = tasks.map(task => {    if (task.id !== id) return { ...task };    found = true;    return { ...task, done: true };  });  return found ? updated : null;}const tasks = [  { id: 1, title: 'Read', done: false },  { id: 2, title: 'Write', done: false },];console.log(completeTask(tasks, 2));console.log(tasks[1].done);console.log(completeTask(tasks, 99));

map creates a fresh object for every task, and only the matching id receives done: true. found records whether the id existed. The output shows task 2 completed, then false for the original, then null for the missing id.

02

Exercise 2: Validate imported tasks

Write parseTasks(text) that parses a JSON array and returns clean task objects. Throw clear errors for malformed JSON, a non-array value, an invalid task shape, or duplicate ids. Test a valid array and the text not json.

your_turn_2.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.jsJavaScript
function parseTasks(text) {  let parsed;  try {    parsed = JSON.parse(text);  } catch {    throw new Error('Invalid JSON');  }  if (!Array.isArray(parsed)) {    throw new Error('Expected an array');  }  const ids = new Set();  return parsed.map(item => {    const valid = item &&      Number.isInteger(item.id) &&      typeof item.title === 'string' &&      typeof item.done === 'boolean';    if (!valid || ids.has(item.id)) {      throw new Error('Invalid task');    }    ids.add(item.id);    return { id: item.id, title: item.title, done: item.done };  });}console.log(parseTasks('[{"id":1,"title":"Ship","done":false}]'));try {  parseTasks('not json');} catch (error) {  console.log(error.message);}

Parsing errors and shape errors produce different messages, which makes failures easier to diagnose. The Set catches duplicate ids before they can enter the tracker. The valid input returns one clean task, and the malformed text prints Invalid JSON.

A SMALL QUESTION. A USEFUL NEXT STEP.

What stayed with you?

Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.

A LITTLE ACTIVE RECALL0 / 3 answered
01Why does createTaskTracker keep nextId separate from the tasks array?
02Why does list return task copies instead of the internal objects?
03What should loadJSON do when one record in an otherwise valid array is malformed?
⚡CODING CHALLENGE
🔒Required to Mark Lesson Complete

Exercise 1: Mark a task complete without mutating

Write completeTask(tasks, id) that returns a new array where the matching task has done set to true. Return null when no task has that id. The input array and its task objects must remain unchanged.

EXPECTED OUTPUT
[{"id":1,"title":"Read","done":false},{"id":2,"title":"Write","done":true}]
false
null
main.jsJavaScript
Ctrl + ↵
Execution Console
Click "Run & Verify" (or press Ctrl + Enter) to test your code against the challenge.

Keep exploring.

The official references behind this lesson, when you want a second angle or the full details.

MODULE 04 · PRACTICAL SELF-CHECK

Pause. Put the pieces together.

You’ve reached the end of Arrays, Objects & Core Data. Before moving on, use this task to check what you can do independently.

Build a task tracker that adds, completes, removes, filters, exports, and re-imports tasks without corrupting its data.

Try it in your own environment and write down the result. This is a self-check; reading completion does not evaluate your code.

Review this module

One lesson closer.

Reading is a start. Trying it yourself makes the connection.

Solve the hands-on coding challenge in the knowledge section to verify your code and unlock lesson completion.