Completing tasks
- Node.js course
- Beginner
- Lesson 86/116
- 6 min
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.
Practice 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.
Starter code
function addTask(tasks, title) {
tasks.push({ title, done: false });
}
function listTasks(tasks) {
tasks.forEach((t, i) => console.log((i + 1) + '. ' + t.title));
}
// Define completeTask, update listTasks, add two tasks, complete the first and listSample 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);Expected output
[x] Ekmek al [ ] Süt al
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Set done to true
function completeTask(tasks, index) {
if (index < tasks.length) {
tasks[index].done = ____;
}
}
function completeTask(tasks, index) {
if (index < tasks.length) {
tasks[index].done = true;
}
}
Explanation: done = true marks the task as completed.
2 How is a completed task shown?
- With (i + 1)
- With length
- With title
- With [x] Correct answer
Explanation: [x] marks a done task, [ ] a pending one.
3 Match the completion parts
| Term | Meaning |
|---|---|
completeTask |
Completion function |
tasks[index].done = true |
Completion assignment |
[x] |
Done task marker |
[ ] |
Pending task marker |