Node.js
Data model
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.
Exercise 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).
Show example 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);
Test yourself
-
Complete the task object
function createTask(id, title) {
return { id: id, title: title, ____: false };
}
Show answer
function createTask(id, title) {
return { id: id, title: title, done: false };
}
-
Match each piece to its role
- createTask
- Creates a task object
- tasks.push
- Adds a task to the array
- tasks.length
- Gives the task count
- done
- Completion status
-
What does tasks.push(createTask(1, "Shopping")) do?
tasks.push(createTask(1, "Alışveriş"))
- Empties the array
- Adds a task to the array
- Sorts the array
- Deletes the task
Show answer
Adds a task to the array — push adds an item to the end of the array.
Next lesson: Business logic