7
1

More than 1 year has passed since last update.

TypeScriptのfindでundefinedが返らないようにする方法

Posted at

findの使用例

findとは、提供されたテスト関数を満たす配列内の最初の値を返すものです。

example.ts
const array1 = [1, 2, 3, 4, 5];

const result = array1.find(element => element > 3);

console.log(result); // 4

例のコードだと、配列の要素で3より大きい最初の要素は4なので、resultには4が返ります。

別に何の問題もないコードに見えるのですが、resultにカーソルを当ててみます。

スクリーンショット 2022-04-17 19.03.55.png

え、undefined…?

そうなんです。findは、テスト関数を満たす配列内の要素がなかった場合に、undefinedを返すようになっているので、仮にテスト関数を満たす要素があったとしてもundefinedが返るようになっています。。

undefinedが返らないようにするにはどうするか

example.ts
const array1 = [1, 2, 3, 4, 5];

const result = array1.find(element => element > 3) ?? 0;

console.log(result);

??をつけることで、テスト関数を満たす要素がなかった場合、つまりundefinedの時に代わりに返す値を設定することができます。

スクリーンショット 2022-04-18 9.15.52.png

これでundefinedが返らないようになりました。めでたしめでたし。

参考記事

7
1
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
7
1