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?

More than 3 years have passed since last update.

【Typescript】Nullish Coalescing と短絡評価

Posted at

はじめに

今回はNullish Coalescing と短絡評価についてです。

Javascriptの場合

const inputData = "";

const storedData = inputData || "DEFAULT TEXT";
console.log(storedData);
const inputData = null;

const storedData = inputData || "DEFAULT TEXT";
console.log(storedData);
const inputData = undefined;

const storedData = inputData || "DEFAULT TEXT";
console.log(storedData);

いずれもinputDataはfalseと評価されて"DEFAULT TEXT"が出力されます。

Typescriptの場合

Nullish Coalescingを使って

const inputData = undefined;

const storedData = userInput ?? "DEFAULT";

console.log(storedData);

と書けます。違いは、

const inputData = "";

const storedData = userInput ?? "DEFAULT";

console.log(storedData);

の時には""がtrueと評価されて空文字が出力されることです。

最後に

また新しいことを覚えたらアウトプットしたいと思います。

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?