Node.js
Adding tasks
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.
Exercise 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.
Show example solution
function addTask(tasks, title) {
tasks.push({ title, done: false });
}
const tasks = [];
addTask(tasks, 'Ekmek al');
console.log(tasks.length);
Test yourself
-
What does push do?
- Removes the first element
- Copies the array
- Reduces the length
- Appends an element to the end
Show answer
Appends an element to the end — push appends a new element to the end of the array.
-
New task object
function addTask(tasks, title) {
tasks.push({ title, done: ____ });
}
Show answer
function addTask(tasks, title) {
tasks.push({ title, done: false });
}
-
Match the appending parts
- tasks.push(...)
- Array append call
- { title, done: false }
- Task object added
- tasks.length
- Task count
- addTask(tasks, ...)
- High-level append
Next lesson: Listing tasks