0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

「?.」って何?

0
Posted at

?. は “存在していればアクセスする、無ければ undefined を返す” 演算子
つまり エラーを出さずに安全にアクセスするための書き方

通常のコード:

baseLabels.length

これ、もし baseLabels が undefined だったら?

普通のアクセスだとエラーになる

Uncaught TypeError: Cannot read properties of undefined (reading 'length')

つまり 処理が落ちる

オプショナルチェイニング(?.)をつけるとエラーにならない。

baseLabels?.length
baseLabels baseLabels?.length の結果
["a", "b"] 2
[] 0
undefined undefined
null undefined
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?