2. 関数と処理の構造化

この章の目的

関数を使って処理をまとめる方法と、ToDoアプリにおける関数設計の実例を学びます。

関数の定義

通常関数:

function greet(name) {
  return "こんにちは、" + name + "さん!";
}

アロー関数:

const greet = (name) => "こんにちは、" + name + "さん!";

関数で処理を整理するメリット

ToDoアプリでの実践例

タスクを画面に表示する処理は renderTask() 関数にまとめられています。

function renderTask(task, ul, groupName) {
  const li = document.createElement("li");

  const checkbox = document.createElement("input");
  checkbox.type = "checkbox";
  checkbox.checked = task.done;

  const span = document.createElement("span");
  span.textContent = task.text;

  const deleteBtn = document.createElement("button");
  deleteBtn.textContent = "削除";

  li.appendChild(checkbox);
  li.appendChild(span);
  li.appendChild(deleteBtn);

  ul.appendChild(li);
}

その他の関数の例

renderGroup(), updateProgress(), openPopup() なども役割ごとに定義されています。

function openPopup() {
  Popup.style.display = "flex";
  document.body.classList.add("modal-open");
}