イディオム - Javascript

  • 作成日:
  • 最終更新日:2025/06/25

イディオムとは?

プログラミングにおける「イディオム(idiom)」とは、ある言語でよく使われる書き方やパターンのことを指します。

これは、慣習的・効率的・読みやすく・エラーが起きにくいとされる書き方であり、その言語に特有の「自然な書き方」とも言えます。

イディオムのサンプル

短絡評価による条件実行

以下のコードは、user.isAdmin が true のときだけ showAdminPanel() を実行します。

const user = { isAdmin: true }

function checkAdmin(){
  console.log("true です。")
}

user.isAdmin && checkAdmin()

デフォルト値の設定

options.data が null や undefined、false などfalsyな値なら、代わりに空オブジェクト {} を使う。

const data = options.data || {};

Null合体演算子(??)でのデフォルト設定(より安全)

|| は false, 0, "" も無視するが、?? は null と undefined だけを無視します。

const data = options.data ?? {};

オプショナルチェイニング(安全なプロパティアクセス)

オプショナルチェイニング(?.) とは、途中のプロパティが undefined や null でもエラーにならず、undefined を返す構文です。

user や profile が null や undefined のときでもエラーにならず、undefined を返します。

const name = user?.profile?.name;

以下のコードでは、user が null のため user.profile を参照しようとするとエラーになります。

const user = null;

const name = user.profile.name;  // TypeError: Cannot read properties of null
console.log(name);

以下のコードでは、user が null でも .profile?.name を安全にスキップできるため、エラーにはならず、結果は undefined になります。

const user = null;

const name = user?.profile?.name;  // undefined
console.log(name);  // undefined

以下もサンプルコードです。

const user1 = {
  profile: {
    name: "Alice"
  }
};

const user2 = {
  profile: null
};

const user3 = null;

console.log(user1?.profile?.name);  // "Alice"
console.log(user2?.profile?.name);  // undefined(profileがnullなので)
console.log(user3?.profile?.name);  // undefined(userがnullなので)

# データがあるかどうかわからないときの安全なアクセス
function printUserName(user) {
  const name = user?.profile?.name ?? "Guest";
  console.log(`Hello, ${name}!`);
}

printUserName({ profile: { name: "Bob" } });  // Hello, Bob!
printUserName({});                            // Hello, Guest!
printUserName(null);                          // Hello, Guest!

スプレッド構文でオブジェクト合成

const fullOptions = { ...defaultOptions, ...userOptions };

条件付きオブジェクトプロパティ

const obj = {
  ...(isAdmin && { role: 'admin' }),
};

Nullチェックの短縮(ガード節)

function printUserInfo(user) {
  if (!user) return;
  if (!user.age) return;

  console.log(`名前: ${user.name}`);
  console.log(`年齢: ${user.age}`);
}

printUserInfo() // データがないため何も表示されない
printUserInfo({ name: "Bob", age: 18 })
printUserInfo({ age: 30 })