Skip to content

15. JavaScript のベストプラクティス

JavaScript のベストプラクティスに従うことは、コードの品質を高め、バグの発生を減少させ、他の開発者との協調作業を容易にします。この章では、主に以下のトピックに焦点を当てて説明します。

  • 一貫性のあるコーディング規約
  • クリーンコードの書き方
  • パフォーマンスの最適化
  • セキュリティ
  • テストとデバッグ

15.1 一貫性のあるコーディング規約

15.1.1 インデントとスペース

コードの可読性を高めるために、インデントやスペースの使用方法を統一しましょう。一般的には 2 スペースか 4 スペースが一般的です。

// Good
function example() {
  let x = 10;
  let y = 20;
  return x + y;
}

// Bad
function example() {
  let x = 10;
  let y = 20;
  return x + y;
}

15.1.2 命名規則

変数名や関数名は、意味のある名前を付けましょう。キャメルケース(camelCase)を使うことが一般的です。

// Good
let userName = "John";
function calculateSum(a, b) {
  return a + b;
}

// Bad
let usrnm = "John";
function calsum(a, b) {
  return a + b;
}

15.2 クリーンコードの書き方

15.2.1 コメント

必要に応じてコメントを挿入し、コードの意図を明確にしましょう。ただし、あまりにも多すぎるコメントは逆効果です。

// Good
// calculateSumは二つの数値の合計を返します
function calculateSum(a, b) {
  return a + b;
}

// Bad
function calculateSum(a, b) {
  // aとbを足してその合計を返す
  return a + b;
}

15.2.2 DRY 原則

「Don't Repeat Yourself」の原則に従い、重複コードを避けるようにしましょう。共通の処理を関数にまとめることが有効です。

// Good
function calculateArea(length, width) {
  return length * width;
}

let area1 = calculateArea(10, 20);
let area2 = calculateArea(15, 25);

// Bad
let area1 = 10 * 20;
let area2 = 15 * 25;

15.3 パフォーマンスの最適化

15.3.1 キャッシュ

頻繁に使うデータはキャッシュして再利用しましょう。頻繁に DOM 操作を行う場合は特に有効です。

// Good
let element = document.getElementById("example");
element.style.color = "blue";
element.style.fontSize = "14px";

// Bad
document.getElementById("example").style.color = "blue";
document.getElementById("example").style.fontSize = "14px";

15.3.2 非同期処理の効率化

非同期処理を利用することで、処理の待ち時間を減らすことができます。

// Good
async function fetchData() {
  const response = await fetch("https://api.example.com/data");
  const data = await response.json();
  console.log(data);
}

// Bad
function fetchData() {
  fetch("https://api.example.com/data")
    .then((response) => response.json())
    .then((data) => console.log(data));
}

15.4 セキュリティ

15.4.1 ユーザー入力のサニタイズ

ユーザーからの入力に対してはサニタイズして、不正なスクリプトの注入を防ぐようにしましょう。

// Example of sanitizing user input
function sanitizeInput(input) {
  return input.replace(/</g, "&lt;").replace(/>/g, "&gt;");
}

let userInput = '<script>alert("Hacked!");</script>';
console.log(sanitizeInput(userInput)); // Outputs: &lt;script&gt;alert("Hacked!");&lt;/script&gt;

15.4.2 安全な API 呼び出し

安全な通信プロトコル(HTTPS)を使用し、API キーやトークンを外部に露出させないようにしましょう。

// Good
fetch("https://api.example.com/data", {
  method: "GET",
  headers: {
    Authorization: "Bearer YOUR_API_TOKEN",
  },
});

// Bad
fetch("http://api.example.com/data", {
  method: "GET",
});

15.5 テストとデバッグ

15.5.1 ユニットテスト

コードの品質を保つために、ユニットテストを実行しましょう。例えば、Jest などのテストフレームワークを使用します。

// Example using Jest
function sum(a, b) {
  return a + b;
}

test("adds 1 + 2 to equal 3", () => {
  expect(sum(1, 2)).toBe(3);
});

15.5.2 デバッグ

デバッグツールを利用して、迅速に問題を特定し解決しましょう。ブラウザの開発者ツールは非常に有用です。

// Using console.log for simple debugging
function calculateSum(a, b) {
  console.log(`a: ${a}, b: ${b}`);
  return a + b;
}

calculateSum(5, 10); // Check the console for the output

以上が JavaScript のベストプラクティスの概要です。これを基に、自分のコードをさらに改善していきましょう。