JavaScript
Adding and listing tasks
Add tasks with push and display them with for...of.
Adding tasks with push
The most common way to add an element to an array is the push method. The call tasks.push(task) puts the task variable at the end of the tasks array and grows its length by one.
push mutates the array in place, so it does not create a new array. You do not need to reassign the array afterwards. It returns the new number of elements.
Listing with for...of
To walk through every element of an array the for...of loop is handy. At each step the loop variable receives one element, with no index to manage.
When you write for (const task of tasks), task becomes each task in turn. Inside you reach its fields with task.title or task.completed. Using const signals that the variable will not be reassigned.
Display format
When listing tasks, picking a readable format matters. Inside console.log you can join text and values with +. For example task.id + ". " + task.title prints something like 1. Buy bread.
You could also add a marker for completed tasks. For now number and title are simple and enough; you can polish the format in later lessons.
Exercise Add and list tasks
Define two functions named addTask and listTasks. addTask should create a task with createTask, push it to tasks and increment nextId. listTasks should walk the tasks with for...of and print each with console.log.
Show example solution
Inside addTask call createTask, push the result and increment nextId. listTasks walks with for...of and prints with console.log.
Example solution:
function addTask(title) {
const task = createTask(title);
tasks.push(task);
nextId++;
}
function listTasks() {
for (const task of tasks) {
console.log(task.id + ". " + task.title);
}
}
Test yourself
-
What happens to the tasks array after calling tasks.push(task)?
- The task is added
- The task is removed
- The array is emptied
- The array is sorted
Show answer
The task is added — push appends the given element to the end of the array and grows its length by one.
-
Complete the for...of header
function listTasks() {
for (const task ____ tasks) {
console.log(task.title);
}
}
Show answer
function listTasks() {
for (const task of tasks) {
console.log(task.title);
}
}
-
Match methods to their jobs
- push
- Adds an element
- for...of
- Iterates values
- console.log
- Prints to screen
Next lesson: Completing and deleting tasks