冗長な定型コードをすっきり置き換える、モダン JavaScript のイディオムと短縮記法です。
必須の短縮パターン
Null合体演算子 (??) とデフォルト値フォールバック
// ?? は null または undefined のみを厳密にチェック(0 や false は保持)
const port = process.env.PORT ?? 3000;
// || はすべての falsy 値(0, "", false, NaN)でフォールバックを実行
const title = customTitle || 'Untitled';
オプショナルチェイニング (?.)
// TypeError を発生させずに深くネストされたプロパティへ安全にアクセス
const street = user?.address?.street;
const firstTag = user?.tags?.[0];
const result = user?.getProfile?.();
短絡実行 (&&)
// 条件が true の場合のみ関数を実行
isLoggedIn && showDashboard();
オブジェクトのプロパティとメソッドの短縮記法
const name = 'Alice';
const age = 30;
// オブジェクトリテラルのプロパティ短縮記法
const user = {
name,
age,
greet() {
return `Hello ${this.name}`;
}
};
配列とオブジェクトの分割代入 (Destructuring)
const { name, age, role = 'member' } = user;
const [first, second, ...rest] = [1, 2, 3, 4, 5];