Data model
- Node.js course
- Beginner
- Lesson 113/116
- 6 min
Set up the object and array structure for the app.
The task object
The basic data unit of our app is the task object. Each task has three properties: id (unique number), title (label) and done (is it complete). Example: { id: 1, title: "Shopping", done: false }.
To make task creation easy we will write a createTask function. It takes id and title, and returns an object whose done property is false. This way every task has the same shape; no missing properties. We take the previous lesson's solution and add this function.
The tasks array
To store tasks we use an array: let tasks = [];. We add a new task with tasks.push(createTask(1, "Shopping")). The array's length property gives the task count.
An array is the natural way to store ordered data. tasks[0] gives the first task, tasks[tasks.length - 1] the last. Later we will use the find method to look up a task by id. For now we add one task and print the array length to see the structure works.
Practice Add the createTask function and call it
Take the previous lesson's solution. Add the createTask(id, title) function with body return { id: id, title: title, done: false };. Define let tasks = [];. Add a task with tasks.push(createTask(1, "Shopping")). Print the count with console.log(tasks.length).
Starter code
const path = require("path");
const DATA_FILE = path.join("data", "tasks.json");
console.log("Ready");
// Define the function that creates a task object
// write here
let tasks = [];
// Add a task and print the count
// write hereSample solution
const path = require("path");
const DATA_FILE = path.join("data", "tasks.json");
function createTask(id, title) {
return { id: id, title: title, done: false };
}
let tasks = [];
tasks.push(createTask(1, "Shopping"));
console.log(tasks.length);Expected output
1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the task object
function createTask(id, title) {
return { id: id, title: title, ____: false };
}
function createTask(id, title) {
return { id: id, title: title, done: false };
}
Explanation: The done property starts false.
2 Match each piece to its role
| Term | Meaning |
|---|---|
createTask |
Creates a task object |
tasks.push |
Adds a task to the array |
tasks.length |
Gives the task count |
done |
Completion status |
3 What does tasks.push(createTask(1, "Shopping")) do?
tasks.push(createTask(1, "Alışveriş"))- Empties the array
- Adds a task to the array Correct answer
- Sorts the array
- Deletes the task
Explanation: push adds an item to the end of the array.