LoginSignup
5
5

More than 3 years have passed since last update.

【備忘録】ショートサーキット評価【TypeScript】

Posted at

ショートサーキット評価

TypeScript,JavaScript 初学者が関数のショートサーキット評価について勉強したのでメモを残す。

ショートサーキット評価(短絡評価)

  • &&||!などの論理演算子を利用する

OR 演算子||左辺が falsy な値の場合、評価は右辺に渡される

const hoge = undefined || null || 0 || NaN || "" || "hoge";
  • undefinednull0NaN''はすべでfalsyなので一番右のhogeが左辺に代入される
  • 初期化を動的に行う際に便利

AND 演算子&&左辺が truthy な値の場合、評価が右辺に渡される

const bar = " " && 100 && [] && {} && "bar";

if 文の代わりに使うこともできる

false && console.log("Hello"); //  (false)
true && console.log("Hello"); //  Hello
false || console.log("Hello"); //  Hello

Nullish Coalescing(??)と Optional Chaining(?.)

const sampleObjects = [
  {
    name: "yasushi",
    age: 27,
  },
  {
    name: "koYasushi,",
  },
  null,
];

for (sample of sampleObjects) {
  const sampleObject = sample ?? { name: "(no name)" };
  const age = sampleObject?.age ?? "( no age )";
  console.log(`${sampleObject.name} is ${age} years old.`);
}
//  yasushi is 27 years old.
//  koYasushi, is ( no age ) years old.
//  (no name) is ( no age ) years old.

Nullish Coalescing(??)

  • ??(nullish coalescing)は左辺が null または undefinedの時に右辺が評価される
  • ||(OR 演算子)と異なり、0 や空文字のような falsy な値はそのまま評価される

Optional Chaining(?.)

  • ?.演算子を使うと、参照が正しいかどうかを明示的に確認せずアクセスできる
  • 今までif文で書いていたエラー処理などが1行で書けるようになる

ショートサーキット評価のまとめ

  • OR 演算子||左辺が falsy な値の場合、評価は右辺に渡される
  • AND 演算子&&左辺が truthy な値の場合、評価が右辺に渡される
  • ??(nullish coalescing)は左辺が null または undefined の時に右辺が評価される

参考

何か指摘等ございましたら、コメントでお願いいたします。

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