Node.js
Completing tasks
Learn to update task status with completeTask.
Completing tasks
To mark a task as done you need to set its done field to true. For this you will write a completeTask(tasks, index) function.
The body is: if (index < tasks.length) { tasks[index].done = true; }. First you check that the index is in bounds; then you set done to true on the task at that position. An out-of-range index is silently ignored.
You will also update listTasks: show [x] when done is true and [ ] when it is false. This way the user can see at a glance which task is done.
Index check
When completeTask is called, you need to check that the index is valid. With if (index < tasks.length) you verify that the index is within the array bounds. An invalid index is silently ignored; no error is thrown.
This check prevents the app from crashing when the user gives a wrong number. For example, in a 2-item list completeTask(tasks, 10) does nothing; tasks[10] would be undefined and accessing .done would throw.
This pattern is common in JavaScript: checking bounds before array access is a basic of safe code. Negative indices are handled the same way.
Exercise Complete a task and list
Define a completeTask(tasks, index) function. Its body is if (index < tasks.length) { tasks[index].done = true; }. Update listTasks to tasks.forEach((t, i) => console.log((t.done ? '[x] ' : '[ ] ') + t.title)). Add two tasks, complete the first, then list them.
Show example solution
function addTask(tasks, title) {
tasks.push({ title, done: false });
}
function listTasks(tasks) {
tasks.forEach((t, i) => console.log((t.done ? '[x] ' : '[ ] ') + t.title));
}
function completeTask(tasks, index) {
if (index < tasks.length) {
tasks[index].done = true;
}
}
const tasks = [];
addTask(tasks, 'Ekmek al');
addTask(tasks, 'Süt al');
completeTask(tasks, 0);
listTasks(tasks);
Test yourself
-
Set done to true
function completeTask(tasks, index) {
if (index < tasks.length) {
tasks[index].done = ____;
}
}
Show answer
function completeTask(tasks, index) {
if (index < tasks.length) {
tasks[index].done = true;
}
}
-
How is a completed task shown?
- With (i + 1)
- With length
- With title
- With [x]
Show answer
With [x] — [x] marks a done task, [ ] a pending one.
-
Match the completion parts
- completeTask
- Completion function
- tasks[index].done = true
- Completion assignment
- [x]
- Done task marker
- [ ]
- Pending task marker
Next lesson: Putting it together