javascript Optional chainingを使用する

javascript Optional chainingを使用する

javascriptで、ES2020の機能になるOptional chainingを使用して、nullやundefinedになる可能性があるオブジェクトのプロパティやメソッドを参照するサンプルコードを記述してます。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 103.0.5060.114

Optional chaining使い方

「Optional chaining」を使用すると、オブジェクト内に「address」が存在する場合は「hoge」が取得でき、

const obj = {
  name: "mebee",
  address: { // 入力の必要のない場合もある    
    apartment: "hoge",
  }
};

const address = obj.address?.apartment;
console.log(address); // addressが存在する場合は「hoge」

addressが存在しない場合は、「undefined」となります。

const obj = {
  name: "mebee",
};

const address = obj.address?.apartment;
console.log(address); // undefined

「Optional chaining」を使用しない場合は、以下のように記述することも可能です。

const address = obj.address && obj.address.apartment;
console.log(address);

例えば、「p」タグのテキストを取得する場合に、「Optional chaining」を使用すると、「id」があればテキストが取得され、

<p id='hoge'>hello</p>

<script>

const elm = document.querySelector('#hoge')?.textContent;
console.log(elm); // hello

</script>

なければ「undefined」となり、エラーとなりません。

<p id='foo'>hello</p>

<script>

const elm = document.querySelector('#hoge')?.textContent;
console.log(elm); // undefined

</script>

上記の場合「Optional chaining」を使用しない場合はエラーとなり、処理が止まります。

const elm = document.querySelector('#hoge').textContent;

// Uncaught TypeError: Cannot read property 'textContent' of null