【JavaScript】オプショナルチェーン(?.)とNull合体演算子(??)の基本!安全に値を取得・初期値設定する方法
JavaScriptでオブジェクトの深い階層にあるデータ(APIから取得したユーザー情報など)を扱う際、途中のデータが undefined や null だったために Uncaught TypeError: Cannot read properties of undefined... というエラーが出てプログラムが止まってしまった経験はありませんか?
また、データが無いときの「初期値(デフォルト値)」を設定するために論理OR演算子(||)を使った結果、「数値の 0 や空文字 "" まで初期値に上書きされてしまった」というのもよくある罠です。
これらの悩みをたった数文字の記号でスマートに解決してくれるのが、モダンJavaScriptの必須構文である「オプショナルチェーン(?.)」と「Null合体演算子(??)」です! 今回は、それぞれの基本的な使い方やコード例、そして2つを組み合わせた実践的なデモをご紹介します!
デモ動作
See the Pen JSのオプショナルチェーン(?.)とNull合体演算子(??)の使い方! by mikanbako (@mikanbako) on CodePen.
demo: JSのオプショナルチェーン(?.)とNull合体演算子(??)の使い方!
実装コード紹介
【HTML】
<div class="l-wrap">
<h2>オプショナルチェーン (?.) & Null合体演算子 (??) デモ</h2>
<p class="p-desc">データの欠損や「数値の 0」が含まれるユーザーデータを切り替えて、表示結果の違いを確認しよう!</p>
<div class="p-demo-box">
<!-- ユーザー切り替えボタン -->
<div class="c-btn-group">
<button class="c-btn is-active js-user-btn" data-user="userA">👤 ユーザーA<br><small>(全データあり)</small></button>
<button class="c-btn js-user-btn" data-user="userB">👤 ユーザーB<br><small>(住所データなし)</small></button>
<button class="c-btn js-user-btn" data-user="userC">👤 ユーザーC<br><small>(ポイントが「0」)</small></button>
</div>
<!-- 選択中の元データ(JSON)表示 -->
<div class="p-data-view">
<div class="c-label">▼ 現在のオブジェクトデータ:</div>
<pre class="c-code-box"><code class="js-raw-data"></code></pre>
</div>
<!-- 取得・表示結果の比較エリア -->
<div class="p-result-area">
<h3 class="c-sec-title">🔍 データの取得結果</h3>
<!-- 1. 住所の取得(?. と ?? の組み合わせ) -->
<div class="c-result-row">
<div class="c-result-head">
<span>① 深い階層の「都市名」を取得</span>
<code>user.profile?.address?.city ?? "未登録"</code>
</div>
<div class="c-result-val js-res-city">-</div>
</div>
<!-- 2. ポイントの取得比較(?? vs ||) -->
<div class="c-result-row">
<div class="c-result-head">
<span>② 「ポイント」を取得</span>
</div>
<div class="c-comp-grid">
<!-- ⭕ Null合体演算子 (??) -->
<div class="c-result-card c-result-card--good">
<div class="c-card-badge">⭕ Null合体演算子 (??)</div>
<code class="c-card-code">user.point ?? "未所持"</code>
<div class="c-card-val js-res-point-nullish">-</div>
<p class="c-card-note js-card-note">※ null / undefined の時だけ初期値になるため、「0」も正しく表示されます!</p>
</div>
<!-- ❌ 論理OR演算子 (||) -->
<div class="c-result-card c-result-card--bad">
<div class="c-card-badge">⚠️ 従来の論理OR (||)</div>
<code class="c-card-code">user.point || "未所持"</code>
<div class="c-card-val js-res-point-or">-</div>
<p class="c-card-note js-card-note">※ 0 を「偽(falsy)」と判定してしまうため、0ポイントなのに「未所持」になってしまいます。</p>
</div>
</div>
</div>
</div>
</div>
</div>
【CSS】
/* ベース装飾 */
.l-wrap {
padding: 40px 20px;
max-width: 650px;
margin: 0 auto;
color: #3e3e3e;
text-align: center;
}
h2 {
margin-bottom: 10px;
font-size: 16px;
color: #1bb4d4;
}
.p-desc {
margin-bottom: 25px;
font-size: 16px;
font-weight: bold;
color: #666;
line-height: 1.6;
}
.p-demo-box {
padding: 30px;
text-align: left;
background: #fff;
border-radius: 12px;
box-shadow: 0 4px 15px rgb(0 0 0 / 5%);
}
/* ボタングループ */
.c-btn-group {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
margin-bottom: 20px;
}
.c-btn {
padding: 10px 8px;
font-size: 15px;
font-weight: bold;
line-height: 1.4;
color: #333;
cursor: pointer;
background: #f1f3f5;
border: 2px solid #ddd;
border-radius: 8px;
transition: 0.2s;
}
.c-btn small {
font-size: 13px;
font-weight: normal;
color: #666;
}
.c-btn:hover {
background: #e9ecef;
}
.c-btn.is-active {
color: #00838f;
background: #e0f7fa;
border-color: #1bb4d4;
}
.c-btn.is-active small {
font-weight: bold;
color: #00838f;
}
/* データ表示エリア */
.p-data-view {
margin-bottom: 25px;
}
.c-label {
margin-bottom: 6px;
font-size: 14px;
font-weight: bold;
color: #666;
}
.c-code-box {
padding: 15px;
overflow-x: auto;
font-family: monospace;
font-size: 14px;
line-height: 1.5;
color: #f8f8f2;
background: #272822;
border-radius: 8px;
}
/* 結果表示エリア */
.c-sec-title {
padding-left: 10px;
margin-bottom: 15px;
font-size: 16px;
color: #1bb4d4;
border-left: 4px solid #1bb4d4;
}
.c-result-row {
padding: 15px;
margin-bottom: 15px;
background: #f8f9fa;
border: 1px solid #dee2e6;
border-radius: 8px;
}
.c-result-head {
display: flex;
flex-wrap: wrap;
gap: 8px;
align-items: center;
justify-content: space-between;
margin-bottom: 8px;
font-size: 14px;
font-weight: bold;
}
.c-result-head code {
padding: 3px 8px;
font-size: 14px;
color: #e83e8c;
background: #e9ecef;
border-radius: 4px;
}
.c-result-val {
padding: 10px;
font-size: 20px;
font-weight: bold;
color: #1bb4d4;
text-align: center;
background: #fff;
border: 1px solid #eee;
border-radius: 6px;
}
/* 比較グリッド */
.c-comp-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 15px;
}
.c-result-card {
display: flex;
flex-direction: column;
align-items: center;
padding: 15px;
text-align: center;
border: 2px solid #ccc;
border-radius: 8px;
}
.c-result-card--good {
background: #f0fbfc;
border-color: #1bb4d4;
}
.c-result-card--bad {
background: #fff5f5;
border-color: #ffc9c9;
}
.c-card-badge {
margin-bottom: 8px;
font-size: 14px;
font-weight: bold;
}
.c-card-code {
padding: 3px 8px;
margin-bottom: 10px;
font-size: 13px;
font-weight: bold;
color: #d6336c;
background: rgb(0 0 0 / 6%);
border-radius: 4px;
}
.c-card-val {
box-sizing: border-box;
width: 100%;
padding: 10px;
margin-bottom: 10px;
font-size: 18px;
font-weight: bold;
color: #333;
background: #fff;
border: 1px solid rgb(0 0 0 / 8%);
border-radius: 6px;
}
.c-result-card--bad .c-card-val.is-bug {
color: #e83e8c;
background: #ffe3e3;
border-color: #ffa8a8;
}
.c-card-note {
display: none;
font-size: 14px;
line-height: 1.4;
color: #666;
text-align: left;
}
.c-card-note.is-show {
display: block;
}
【JavaScript】
// テスト用の3パターンのユーザーデータ
const users = {
// パターン1:すべてのデータが揃っている
userA: {
name: '田中 太郎',
profile: { address: { city: '札幌市' } },
point: 1500
},
// パターン2:profileの中身(address)が存在しない&pointも未定義
userB: {
name: '佐藤 花子',
profile: null
// pointプロパティ自体がない(undefined)
},
// パターン3:pointが「0」になっている(重要!)
userC: {
name: '鈴木 一郎',
profile: { address: { city: '函館市' } },
point: 0
}
};
// DOM要素の取得
const buttons = document.querySelectorAll('.js-user-btn');
const rawDataEl = document.querySelector('.js-raw-data');
const resCityEl = document.querySelector('.js-res-city');
const resPointNullishEl = document.querySelector('.js-res-point-nullish');
const resPointOrEl = document.querySelector('.js-res-point-or');
const notes = document.querySelectorAll('.js-card-note');
// データを画面に反映する関数
const updateView = (userKey) => {
const user = users[userKey];
// 元データのJSONを表示
rawDataEl.textContent = JSON.stringify(user, null, 2);
// 💡 1. オプショナルチェーン (?.) と Null合体演算子 (??) で都市名を安全に取得!
// profile が null でもエラーにならず undefined を返し、?? で「未登録」になる
const city = user.profile?.address?.city ?? '未登録';
resCityEl.textContent = city;
// 💡 2. ポイントの取得比較(?? vs ||)
// ⭕ Null合体演算子:null または undefined の時だけ右側の「未所持」になる(0 はそのまま 0 として残る!)
const pointNullish = user.point ?? '未所持';
resPointNullishEl.textContent = typeof pointNullish === 'number' ? `${pointNullish} pt` : pointNullish;
// ❌ 論理OR演算子:0 も false 扱いになるため、0pt なのに「未所持」にされてしまう!
const pointOr = user.point || '未所持';
resPointOrEl.textContent = typeof pointOr === 'number' ? `${pointOr} pt` : pointOr;
// ユーザーC(0ポイント)の時に || 側のバグを強調表示する
if (userKey === 'userC') {
resPointOrEl.classList.add('is-bug');
notes.forEach(note => {
note.classList.add('is-show');
});
} else {
resPointOrEl.classList.remove('is-bug');
notes.forEach(note => {
note.classList.remove('is-show');
});
}
};
// ボタンクリック時の切り替えイベント
buttons.forEach(btn => {
btn.addEventListener('click', () => {
buttons.forEach(b => b.classList.remove('is-active'));
btn.classList.add('is-active');
updateView(btn.dataset.user);
});
});
// 初期表示(ユーザーA)
updateView('userA');
使い方とコード例
オプショナルチェーン(?.)とは?
オプショナルチェーン(Optional chaining:?.) は、ドット(.)の代わりに ?. を使ってプロパティにアクセスすることで、「もし途中の要素が null や undefined だったら、エラーを出さずにそこで処理を止めて undefined を返す」という安全な演算子です。
【従来の書き方と ?. の比較】
const user = {
name: '佐藤',
profile: null // 住所データ(address)がまだ登録されていない!
};
// ❌ そのままアクセスすると、null の中を探そうとしてエラーでプログラムが停止する!
// console.log(user.profile.address.city); // Uncaught TypeError!
// 🔺 従来の回避策:&& で段階的にチェックする必要があり、コードが長くなる
const cityOld = user.profile && user.profile.address && user.profile.address.city;
// ⭕ オプショナルチェーン (?.) を使ったモダンな書き方
// profile が null の時点で安全にストップし、エラーにならず undefined が返る!
const cityNew = user.profile?.address?.city;
console.log(cityNew); // 結果: undefined
また、オブジェクトのプロパティだけでなく、「存在するかわからない関数の呼び出し」や「配列の要素へのアクセス」、さらには「DOM要素の操作」にも使えます!
// 配列が存在するかわからない時(?.[インデックス])
const firstItem = data.items?.[0];
// メソッド(関数)が存在するかわからない時(?.())
user.customMethod?.();
// 画面上に要素が無いかもしれない時のDOM操作にも便利!
const titleText = document.querySelector('.js-missing-title')?.textContent;
Null合体演算子(??)とは?(|| との違い)
Null合体演算子(Nullish coalescing operator:??) は、左辺 ?? 右辺 の形で記述し、「左側の値が null または undefined の時だけ、右側の値(初期値)を返す」という演算子です。
従来は初期値の設定に論理OR演算子(||)がよく使われていましたが、|| には「数値の 0 や空文字 "" まで偽(falsy)と判定して初期値で上書きしてしまう」という厄介な弱点がありました。
【|| と ?? の挙動の違い】
const point = 0; // ポイントが「0pt」という立派なデータ!
// ❌ 論理OR演算子 (||) の場合
// 0 は falsy(偽)と判定されるため、勝手に初期値の 100 にすり替わってしまう!
console.log(point || 100); // 結果: 100 (バグの原因!)
// ⭕ Null合体演算子 (??) の場合
// null と undefined 以外はすべて有効な値として扱うため、0 が正しく守られる!
console.log(point ?? 100); // 結果: 0
// もちろん null や undefined の時はしっかり初期値(100)になる
const emptyPoint = undefined;
console.log(emptyPoint ?? 100); // 結果: 100
?. と ?? を組み合わせて使おう
「?. で安全に深い階層の値を取りに行き、もし結果が undefined(データなし)だったら ?? で初期値を入れる」という組み合わせが鉄板パターンとしてセットで使われます!
// 都市名があればそれを表示し、途中のデータが欠けていれば「未登録」と表示する
const userCity = user.profile?.address?.city ?? '未登録';
たった1行でエラー防止と初期値の設定が完結するため、コードの可読性と安全性が向上します。
補足:公式ドキュメント
まとめ
今回はモダンJavaScriptで欠かせない「オプショナルチェーン(?.)」と「Null合体演算子(??)」について解説しました。
- オプショナルチェーン(
?.):途中にnullやundefinedがあってもエラーで止めずにundefinedを返してくれる安全装置。 - Null合体演算子(
??):nullまたはundefinedの時だけ初期値を設定し、数値の0や空文字""を誤って消してしまうバグを防いでくれる演算子。
この2つをセットで使いこなせば、冗長なif 文やエラー対策コードを減らし、スッキリとした堅牢なコードが書けるようになります。ぜひ日々の開発に取り入れてみてくださいね!