Now that you know how to store and inspect values, it is time to write reusable code and transform arrays efficiently. This post also follows the concept → code → reason rhythm.
Key terms
- Function: a reusable bundle of code that accepts inputs, performs work, and returns a result.
- Arrow function: the
() => {}shorthand that keeps callbacks compact. - Callback: a function passed into another function to be executed later—commonly used in array methods and events.
- Array methods: built-ins such as
map,filter, andreducethat reshape or summarize arrays. - Chaining: connecting multiple methods with dots so data flows through several stages.
Core ideas
- Functions: name the work you want to reuse. Always be explicit about inputs (parameters) and outputs (return values).
- Arrow functions:
const fn = () => {}defines a short function expression. Without braces you can express single-line calculations cleanly. - Array methods:
maptransforms every element,filterkeeps only the elements that meet a condition, andreducecondenses the array into a single value or object. Each one receives a callback. - Chaining: linking array methods keeps the transformation readable and lets you narrate UI state updates.
Code examples
function add(a, b) {
return a + b;
}
const multiply = (a, b) => a * b;
add is a function declaration and multiply is an arrow function expression. Use whichever reads best as long as the inputs and outputs match the job.
const scores = [70, 85, 90];
const raisedScores = scores.map((score) => score + 5);
const posts = [
{ title: "Intro", published: true },
{ title: "Draft", published: false },
];
const publishedPosts = posts.filter((post) => post.published);
const total = scores.reduce((sum, score) => sum + score, 0);
Combine map, filter, and reduce to solve repetitive tasks such as festival schedules or club rosters.
const users = [
{ name: "Minji", active: true },
{ name: "Jisoo", active: false },
{ name: "Hojun", active: true },
];
const activeNames = users
.filter((user) => user.active)
.map((user) => user.name);
console.log(activeNames); // ["Minji", "Hojun"]
const orders = [
{ price: 12000, type: "ramen" },
{ price: 4500, type: "coffee" },
{ price: 8000, type: "ramen" },
];
const totalByType = orders.reduce((acc, order) => {
const nextTotal = (acc[order.type] ?? 0) + order.price;
return { ...acc, [order.type]: nextTotal };
}, {});
console.log(totalByType); // { ramen: 20000, coffee: 4500 }
The ?? (nullish coalescing) operator inserts a default when a value is missing so the sum never hits undefined.
Why it matters
- When a school event page needs “hide closed registrations,” one
filtergets it done. - Calculating inventory counts or response stats on the fly lets you refresh UI without a round trip to the server.
- Clear function names make it easy in reviews to explain “this function takes X input and refreshes Y view.”
Practice
- Follow along: build a
todosarray, implementtoggleTodo(id)to flip completion, then usefilterto print completed and pending lists. - Extend: use
reduceto build an object of tag frequencies and convert that object into data ready for a list UI. - Debug: omit the
reduceinitial value on purpose, note theTypeError, then add the initial value to fix it. - Done when: your
filter -> map -> reducechain outputs the expected arrays plus the stats object.
Wrap-up
Once you are fluent with functions and array methods you can describe data behavior in a single sentence. The next post connects these flows to the screen by selecting DOM elements and wiring events.
💬 댓글
이 글에 대한 의견을 남겨주세요