Adding tasks
- Node.js course
- Beginner
- Lesson 84/116
- 6 min
Learn to add tasks with the addTask function.
Adding tasks
A single task object is useful; but for a list you need to hold many tasks together. For this you will use an array and an addTask function.
The addTask(tasks, title) function pushes a new task object into the given tasks array. Its body is: tasks.push({ title, done: false }). The push method appends an element to the end of the array.
Example: const tasks = []; addTask(tasks, 'Ekmek al');. After this call tasks.length is 1. Each addTask call grows the array by one element.
Appending to an array
The push method appends an element to the end of a JavaScript array. The original array changes; the new length is returned. In a task list, each addTask call uses push to add a task object.
Example: const tasks = []; tasks.push({ title: 'a', done: false }); tasks.push({ title: 'b', done: false });. After these calls tasks.length is 2 and tasks[0].title gives 'a'.
You can read the array's length with tasks.length. This property is the fastest way to learn how many tasks there are. You can also use the length when printing the list.
Practice Add a task and count
Define a function addTask(tasks, title). Its body should call tasks.push({ title, done: false }). Define an empty tasks array, add one task with addTask(tasks, 'Ekmek al'), and print tasks.length with console.log.
Starter code
// Define addTask, add one task and print the countSample solution
function addTask(tasks, title) {
tasks.push({ title, done: false });
}
const tasks = [];
addTask(tasks, 'Ekmek al');
console.log(tasks.length);Expected output
1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does push do?
- Removes the first element
- Copies the array
- Reduces the length
- Appends an element to the end Correct answer
Explanation: push appends a new element to the end of the array.
2 New task object
function addTask(tasks, title) {
tasks.push({ title, done: ____ });
}
function addTask(tasks, title) {
tasks.push({ title, done: false });
}
Explanation: done: false means the new task is not done.
3 Match the appending parts
| Term | Meaning |
|---|---|
tasks.push(...) |
Array append call |
{ title, done: false } |
Task object added |
tasks.length |
Task count |
addTask(tasks, ...) |
High-level append |