JavaScript
Tutorial: arrays in JavaScript - organize a to-do list
Master the most common array methods (push, filter, map) by building a simple to-do list.
An array is an ordered list of things: pending tasks, cart items, names of friends who never reply to the group chat. Today you'll actually learn to manipulate them, not just create them.
Step 1: create an array and add items
const tasks = ['Buy milk', 'Study JavaScript'];
tasks.push('Take out the trash');
console.log(tasks);
// ['Buy milk', 'Study JavaScript', 'Take out the trash']
.push() adds an item to the end of the array. Simple, direct, no drama.
Step 2: remove items with .filter()
const doneTasks = ['Buy milk'];
const pendingTasks = tasks.filter(
(task) => !doneTasks.includes(task)
);
console.log(pendingTasks);
// ['Study JavaScript', 'Take out the trash']
.filter() creates a new array with only the elements that match a condition. Here we keep the tasks that are NOT in the done list. The original array stays untouched (Filter doesn't destroy, it creates).
Step 3: transform each item with .map()
const tasksWithEmoji = tasks.map((task) => `📌 ${task}`);
console.log(tasksWithEmoji);
// ['📌 Buy milk', '📌 Study JavaScript', '📌 Take out the trash']
.map() loops through the array and returns a new one with each element transformed. It's like running each task through a machine that stamps a label on top.
Step 4: loop through the array with .forEach()
tasks.forEach((task, index) => {
console.log(`${index + 1}. ${task}`);
});
.forEach() is for when you just want to "do something" with each item (like printing it), without creating a new array.
What did you just learn?
- How to add items with
.push(). - How to filter with
.filter()without modifying the original array. - How to transform data with
.map()and loop through it with.forEach().