β Build a To-Do List
A working CLI to-do list using arrays of objects. Practices: arrays, objects, loops, functions, I/O.
What You'll Build
A list of tasks you can add to, mark complete, and remove. We'll keep state in an array of objects.
Step 1 β the Data Shape
javascript
let todos = [];
// Each todo: { id, task, done }
function add(task) {
todos.push({ id: Date.now(), task, done: false });
}
function complete(id) {
const t = todos.find(x => x.id === id);
if (t) t.done = true;
}
function remove(id) {
todos = todos.filter(x => x.id !== id);
}
function list() {
todos.forEach(t => console.log(`${t.done ? "β" : "Β·"} ${t.task}`));
}Step 2 β Exercise It
javascript
add("Buy milk");
add("Read chapter 3");
add("Call Mom");
list();
// Β· Buy milk
// Β· Read chapter 3
// Β· Call Mom
complete(todos[1].id);
list();
// Β· Buy milk
// β Read chapter 3
// Β· Call MomStep 3 β Make It Persistent (Browser)
javascript
function save() { localStorage.setItem("todos", JSON.stringify(todos)); }
function load() { todos = JSON.parse(localStorage.getItem("todos") || "[]"); }Stretch Goals
- Add a "due date" field. Sort by it.
- Add categories. Filter the list.
- Add a simple HTML page that calls these functions on user input.