[JavaScript Series 3] Reusing Code and Transforming Data with Functions and Array Methods

한국어 버전

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

  1. Function: a reusable bundle of code that accepts inputs, performs work, and returns a result.
  2. Arrow function: the () => {} shorthand that keeps callbacks compact.
  3. Callback: a function passed into another function to be executed later—commonly used in array methods and events.
  4. Array methods: built-ins such as map, filter, and reduce that reshape or summarize arrays.
  5. 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: map transforms every element, filter keeps only the elements that meet a condition, and reduce condenses 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 filter gets 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 todos array, implement toggleTodo(id) to flip completion, then use filter to print completed and pending lists.
  • Extend: use reduce to build an object of tag frequencies and convert that object into data ready for a list UI.
  • Debug: omit the reduce initial value on purpose, note the TypeError, then add the initial value to fix it.
  • Done when: your filter -> map -> reduce chain 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.

💬 댓글

이 글에 대한 의견을 남겨주세요