[JavaScript Series 6] Organize Code with Objects, Destructuring, and Modules

한국어 버전

As your JavaScript programs grow and handle more data, organizing your code becomes essential. Objects bundle related values, destructuring lets you pull only what you need from that bundle, and modules keep those bundles in separate files. This chapter is split into the core loop (objects / destructuring / module basics) and optional extensions (service and page separation), so lock in the core flow first.

Key terms

  1. Destructuring assignment: syntax for plucking specific values from an object or array and assigning them directly to variables.
  2. Module: a function-focused file that cooperates with other files through import/export.
  3. import/export: the keywords that let you share functions between modules.
  4. BASE_URL: a shared prefix for API calls that you extract into a constant.

Understanding the concepts

  • Object literals: key-value pairs inside braces that represent a cohesive unit such as a user profile or card content.
  • Destructuring assignment: makes it obvious which pieces of the object a function actually consumes and keeps declarations short.
  • Modules (import/export): a standard way to break your code by responsibility so browsers and Node can load it.
  • Shared constants: selectors, API hosts, and role names live in one place so every file stays in sync.

Code examples

Start with the smallest example: create one object and destructure a single value.

const laptop = { brand: "Brand A", model: "Air 13", price: 1_200_000 };
const { brand } = laptop;
console.log(`${brand} laptop`);

➡️ Remember the feeling of “grab one value from a box” and the next examples will click quickly.

const user = {
  name: "Jiyoon",
  email: "[email protected]",
  preferences: {
    theme: "light",
    language: "ko",
  },
  greet() {
    console.log(`Hello ${this.name}`);
  },
};

const {
  name,
  preferences: { theme, language },
} = user;

Nested destructuring lets you pull exact properties in one statement, so you avoid typing user.preferences.theme repeatedly.

function createGreeting({ name, language = "en" }) {
  return language === "en" ? `Hello ${name}` : `${name}, welcome in ${language}`;
}

createGreeting({ name: "Haram" });

Destructuring parameters keep the function body short and reveal “which inputs are required?” right inside the signature.

// utils/date.js
export function formatDate(date) {
  return new Intl.DateTimeFormat("ko", { dateStyle: "medium" }).format(date);
}

// components/post-card.js

export function renderPost({ title, createdAt }) {
  return `<article><h3>${title}</h3><time>${formatDate(createdAt)}</time></article>`;
}

When modules split responsibilities like this, changing the date format only touches utils/date.js. Cheat sheet: “utility function → utils”, “visual snippet → components” so teammates instantly know where to look.

// services/api.js
const BASE_URL = "https://starter-api.example";

export async function fetchStudent({ id }) {
  const response = await fetch(`${BASE_URL}/students/${id}`);
  if (!response.ok) throw new Error("Failed to load student data");
  const { name, major, club } = await response.json();
  return { name, major, club };
}

// pages/profile.js

export async function renderProfile(id) {
  const { name, major } = await fetchStudent({ id });
  return `<h1>${name}</h1><p>${major}</p>`;
}

Separating data, UI, and page files keeps the flow readable even when someone only touches one part. Treat this as optional depth—apply it as the project grows.

Why it matters

  • Objects remove the need to remember argument order because everything travels as named properties.
  • Destructuring spells out which pieces of data a function actually depends on, which speeds up reviews.
  • Modules isolate state management, rendering, and API calls so collaboration conflicts drop and framework migrations hurt less.

Practice

  • Follow along: build a todo list as an array of objects, then destructure title and completed when rendering.
  • Extend: split your demo into data.js, services.js, and components.js, wiring them together with import/export.
  • Debug: intentionally break an import path to study the error, then fix it; remove a destructuring default to note what becomes undefined.
  • Done when: at least three modules import/export each other to render todos, and function signatures shrink to three parameters or fewer.

Key takeaways

Objects and destructuring shrink your function signatures, and modules clarify file ownership. Next we will use this structure to connect state and rendering in a mini project.

💬 댓글

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