Node.js
Business logic
Write business rules with functions and conditional logic.
Business logic functions
We set up the data model; now we add business logic. We will write two functions: addTask(title) adds a new task, completeTask(id) marks a task as done.
addTask auto-generates an id: const id = tasks.length + 1;. Each new task gets the next number. It builds the object with createTask and appends it with tasks.push. completeTask finds the task with tasks.find and sets task.done = true. These two functions form the core behavior of the app. We take the previous lesson's solution and add them.
Searching with find
The completeTask function uses tasks.find. find returns the first item that matches a condition. Example: tasks.find(function(t) { return t.id === id; }). This finds the task whose id matches.
We update the found task with if (task) { task.done = true; }. The if (task) check guards against the case where find returns undefined when no id matches. This is a real use of conditional logic: update only if the task exists. We will reuse the same pattern later with filter to count completed tasks.
Exercise Add the addTask and completeTask functions
Take the previous lesson's solution. Add addTask(title): generate id with const id = tasks.length + 1;, append with tasks.push(createTask(id, title)). Add completeTask(id): find with tasks.find, set task.done = true. The last lines are ready: addTask("Email"); completeTask(1); console.log(tasks[0].done);
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"));
function addTask(title) {
const id = tasks.length + 1;
tasks.push(createTask(id, title));
}
function completeTask(id) {
const task = tasks.find(function(t) { return t.id === id; });
if (task) { task.done = true; }
}
addTask("Email");
completeTask(1);
console.log(tasks[0].done);
Test yourself
-
Match each piece to its role
- addTask
- Adds a new task
- completeTask
- Marks a task done
- tasks.find
- Finds by id
- tasks.length + 1
- Generates a new id
-
Complete the completeTask body
function completeTask(id) {
const task = tasks.find(function(t) { return t.id === id; });
if (task) { task.____ = true; }
}
Show answer
function completeTask(id) {
const task = tasks.find(function(t) { return t.id === id; });
if (task) { task.done = true; }
}
-
What does tasks.find return?
tasks.find(function(t) { return t.id === 5; })
- All tasks
- The number of tasks
- The first task matching the condition
- Yeni bir dizi
Show answer
The first task matching the condition — find returns the first matching item.
Next lesson: fs persistence