Listing tasks
- Node.js course
- Beginner
- Lesson 85/116
- 6 min
Learn to print tasks formatted with listTasks.
Listing tasks
After adding tasks you need to print them. For this you will write a listTasks(tasks) function. It walks the array and prints each task as a formatted line.
To walk the list, forEach is a good fit: tasks.forEach((t, i) => console.log(...)). Here t is the task object and i is its position. For each task you print a line like (i + 1) + '. ' + t.title.
Example: with two tasks the output is 1. Ekmek al and 2. Süt al. We use i + 1 because array indices start at 0 but humans prefer counting from 1.
Formatted output
When printing a list, presenting tasks in a readable format matters. Each line has a number, a dot, and the task title: (i + 1) + '. ' + t.title.
In JavaScript string concatenation uses the + operator. Adding a number and a string gives a string: 1 + '. ' produces '1. '. Appending t.title gives the full line.
With two tasks the output is two lines. Each line is printed with a separate console.log call, so each task appears on its own line.
Practice List two tasks
Define a listTasks(tasks) function. Its body should call tasks.forEach((t, i) => console.log((i + 1) + '. ' + t.title)). The addTask function is provided in the starting code. Add two tasks and list them with listTasks(tasks).
Starter code
function addTask(tasks, title) {
tasks.push({ title, done: false });
}
// Define listTasks, add two tasks and list themSample solution
function addTask(tasks, title) {
tasks.push({ title, done: false });
}
function listTasks(tasks) {
tasks.forEach((t, i) => console.log((i + 1) + '. ' + t.title));
}
const tasks = [];
addTask(tasks, 'Ekmek al');
addTask(tasks, 'Süt al');
listTasks(tasks);Expected output
1. Ekmek al 2. Süt al
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How does the list output start?
- 1. Ekmek al Correct answer
- 0. Ekmek al
- Ekmek al
- [0] Ekmek al
Explanation: with i + 1 the first task at index 0 prints as number 1.
2 Match the listing parts
| Term | Meaning |
|---|---|
forEach |
Method to walk the array |
(t, i) |
Callback parameters |
i + 1 |
Position number |
t.title |
Task title |
3 Formatted line
tasks.forEach((t, i) => console.log((i + 1) + '. ' + ____));
tasks.forEach((t, i) => console.log((i + 1) + '. ' + t.title));
Explanation: t.title adds the task title to the line.