JavaScriptのNull合体演算子を使った実践的な例

JavaScriptには、Null合体演算子(??)という便利な演算子があります。この演算子は、左側の式がnullまたはundefinedである場合、右側の式を返します。つまり、nullまたはundefinedを扱う際に、簡潔にコードを記述することができます。

この記事では、JavaScriptのNull合体演算子の基本的な使い方を実例で紹介します。

const foo = null;
let msg = foo ?? 'sample';
console.log(msg); // "sample"
const foo = undefined;
let msg = foo ?? 'sample';
console.log(msg); // "sample"
const foo = 'the world';
let msg = foo ?? 'sample';
console.log(msg); // "the world"

0や空文字などは値をそのまま返すので注意が必要です。

const foo = 0;
let msg = foo ?? 'sample';
console.log(msg); // 0
const foo = '';
let msg = foo ?? 'sample';
console.log(msg); // ""
const foo = false;
let msg = foo ?? 'sample';
console.log(msg); // false
このエントリーをはてなブックマークに追加
にほんブログ村 IT技術ブログへ

スポンサードリンク

関連コンテンツ

コメント

メールアドレスが公開されることはありません。 が付いている欄は必須項目です