Project final - To-do list
Finalize the to-do app and make all commands work.
Two final functions
The app can now add, list, complete and delete tasks. Finally we add two small pieces: findTask to find a task by id and toggleTask to flip the completion state.
These two functions introduce the find method in place of the findIndex and filter from earlier lessons. This finalizes the app and makes every command usable.
Toggling the state
Sometimes instead of just completing a task you want to toggle it: if it is done, make it pending; if pending, mark it done. The ! operator flips a boolean for this.
When you write task.completed = !task.completed, the value becomes false if it was true and true if it was false. This is very handy for buttons that switch state on every click.
find versus findIndex
find and findIndex work alike but return different things. find returns the first matching element itself; findIndex returns its position.
When you need the element rather than the position, find is shorter. For example tasks.find(function (task) { return task.id === id; }) returns the task object directly. If nothing matches you get undefined.
Exercise Find a task and toggle its state
Define two functions named findTask and toggleTask. findTask should return the task whose id matches using tasks.find. toggleTask should find the task with findTask and flip its completed value with !; if the task is not found, do nothing.
Show example solution
findTask returns the match with tasks.find. toggleTask first finds it, then flips the completed value.
Example solution:
function findTask(id) {
return tasks.find(function (task) {
return task.id === id;
});
}
function toggleTask(id) {
const task = findTask(id);
if (task) {
task.completed = !task.completed;
}
}
Test yourself
-
What is the purpose of the toggleTask function?
- It deletes the task
- It flips the completion
- It adds the task
- It finds the task
Show answer
It flips the completion — toggleTask flips the completed value of a task, turning true into false and false into true.
-
Complete the toggle line
function toggleTask(id) { const task = findTask(id); if (task) { task.completed = !____; } }Show answer
function toggleTask(id) { const task = findTask(id); if (task) { task.completed = !task.completed; } } -
Match methods to their use cases
- find
- Returns first match
- findIndex
- Returns position
- !
- Flips a boolean